Condensing a sparse array in Javascript?

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

    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.

    var ts = 0,
        te = 0,
    sparse = new Array(10000000),
     dense = [];
    [sparse[2499999], sparse[4999999], sparse[9999999]] = ["first one", "middle one", "last one"];
    
    ts = performance.now();
    dense = Object.keys(sparse).map(k => sparse[k]);
    te = performance.now();
    console.log(dense, "Okeys and map resulted in :" +(te-ts)+ "msecs");
    
    dense = [];
    
    ts = performance.now();
    for (var key in sparse) dense.push(sparse[key]);
    te = performance.now();
    console.log(dense, "for in loop resulted in :" +(te-ts)+ "msecs");
    
    dense = [];
    
    ts = performance.now();
    dense = sparse.filter(function (x) { return x !== undefined && x !== null; });
    te = performance.now();
    console.log(dense, "Array filter resulted in :" +(te-ts)+ "msecs");
    
    dense = [];
    
    ts = performance.now();
    for (var i = 0, len = sparse.length; i < len; i++) sparse[i] !== undefined &&
                                                       sparse[i] !== null      &&
                                                       dense.push(sparse[i]);
    te = performance.now();
    console.log(dense, "For loop resulted in :" +(te-ts)+ "msecs");

提交回复
热议问题