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]
I can't believe there is so limited answers in here. First of all i think there are better, faster solutions to condensing a sparse array. I guess a sparse array doesn't mean an array with holes of undefined items (What exactly is a dense array?). A sparse array should be an array where actually there are no keys exists other than the keys which belong to the existing but sparse values. So if we iterate over the keys we should be doing our job more efficiently and faster.
Ok i compiled a test below to show you the performance of several methods to condense a sparse array.
In ES2017 (ES8) this is as easy as
Object.values(sparseArray)
For example:
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
ornull
.A cross browser solution using
filter
DEMO.
In vanilla JS, works on all browsers:
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:
This works since
filter()
skips missing elements and only returnstrue
if x is notundefined
ornull
.If
filter()
is not supported, this will compact a sparse array:An exact equivalent of the
filter()
example is:If you want to include underscore.js in your code, you can use the compact function on your array.