Condensing a sparse array in Javascript?

You can use filter() which is compatible with Firefox, Chrome, IE 9, Opera, and Safari web browsers.

According to David Flanagan, in Javascript: The Definitive Guide, an easy way of transforming a sparse array to a dense array is to use a filter on it like so:

var dense = sparse.filter(function (x) { return x !== undefined && x != null; });

This works since filter() skips missing elements and only returns true if x is not undefined or null.

If filter() is not supported, this will compact a sparse array:

var compacted = [];

for(var i = 0; i < sparse.length; i++)
    if(i in sparse)
        compacted.push(sparse[i]);

An exact equivalent of the filter() example is:

var compacted = [];

for(var i = 0; i < sparse.length; i++)
    if(sparse[i] != null)
        compacted.push(sparse[i]);

In ES2017 (ES8) this is as easy as Object.values(sparseArray)

For example:

const sparseArray = [, , 'foo', 'bar', , 'baz', ,];
const compactArray = Object.values(sparseArray);
console.log(compactArray);

Note though that this method only removes gaps, shifting down the indexes of existing array elements as required. It does not remove elements explicitly set to undefined or null.


In vanilla JS, works on all browsers:

function filt(a) { 
 var b = []; 
 for(var i = 0;i < a.length;i++) { 
  if (a[i] !== undefined && a[i] !== null) { 
   b.push(a[i]); 
  }
 } 
 return b; 
}

> filt([1,undefined,3])
[1, 3]