Condensing a sparse array in Javascript?

后端 未结 6 1893
暗喜
暗喜 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:58

    filter is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter in ECMA-262 implementations which do not natively support it. Reference : MDN.

    A cross browser solution using filter

    if (!Array.prototype.filter) {  // Add the filter method to the 'Array prototype' if it's not available
        Array.prototype.filter = function(fun /*, thisp*/) {
            var len = this.length >>> 0;
            if (typeof fun != "function") {
                throw new TypeError();
            }
    
            var res = [];
            var thisp = arguments[1]; 
            for (var i = 0; i < len; i++) {
                if (i in this) {
                    var val = this[i];
                    if (fun.call(thisp, val, i, this)) {
                        res.push(val);
                    }
                }
            }
            return res;
        };
    }
    
    var sparse = [];
    sparse[1] = undefined;
    sparse[5] = 3;
    sparse[10] = null;
    
    dense=sparse.filter(function(a){ //Call the `filter` method
        return a!== undefined && a != null;
    });
    

    DEMO.

提交回复
热议问题