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]
[3]instead of[undefined, 3, null]?1 in sparse === truebut0 in sparse === false, so only the ones where you didn’t set values are really missing. if you want to do that, the answer isvar dense = []; sparse.forEach(function(e) { dense.push(e) }), as this only loops over the existing items