Ivan Ivan - 1 year ago 94
Javascript Question

Condensing a sparse array in Javascript?

I have an array of elements where the entries are sparse. How can I easily condense the sparse array into a dense array so that I don't have to keep checking for null and undefined values every time I loop through the data?

Here is some example data:

var sparse = [];
sparse[1] = undefined;
sparse[5] = 3;
sparse[10] = null;

var dense = sparseToDenseArray(sparse);
// dense should be [3]

Answer Source

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) { 
 return b; 

> filt([1,undefined,3])
[1, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download