Need to reset just the indexes of a Javascript array

◇◆丶佛笑我妖孽 提交于 2019-12-04 06:16:28

This is easily done natively using Array.filter:

resetArr = orgArr.filter(function(){return true;});

You could just copy all the elements from the array into a new array whose indices start at zero.

E.g.

function startFromZero(arr) {
    var newArr = [];
    var count = 0;

    for (var i in arr) {
        newArr[count++] = arr[i];
    }

    return newArr;
}

// messed up array
x = [];
x[3] = 'a';
x[4] = 'b';
x[5] = 'c';

// everything is reordered starting at zero
x = startFromZero(x);
hallodom

Perhaps "underscore.js" will be useful here.

The _.compact() function returns a copy of the array with no undefined.

See: http://underscorejs.org/#compact

Easy,

var filterd_array = my_array.filter(Boolean);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!