Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 466
Ivan Avatar asked Jul 25 '12 23:07

Ivan


Video Answer


2 Answers

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.

like image 171
GOTO 0 Avatar answered Sep 30 '22 10:09

GOTO 0


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]);
like image 32
5 revs, 3 users 53%user1479055 Avatar answered Sep 30 '22 10:09

5 revs, 3 users 53%user1479055