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
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]);