Condensing a sparse array in Javascript?

后端 未结 6 1891
暗喜
暗喜 2020-12-11 16:59

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

6条回答
  •  情话喂你
    2020-12-11 17:40

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

提交回复
热议问题