开发者

javascript sort 2d arrays and remove some elements

开发者 https://www.devze.com 2023-03-13 15:19 出处:网络
i have created anarray in JS var myArray=[ [el1开发者_运维知识库,pos1,width1,active1], [el2,pos2,width2,active2],

i have created an array in JS

var myArray=[
 [el1开发者_运维知识库,pos1,width1,active1],
 [el2,pos2,width2,active2],
 [el3,pos4,width3,active3],
 [el4,pos1,width4,active4]
];

how can i remove elements with active(i)=0? then i need to sort it by pos(i) ascending can you give me some samples/solution?


As said, there are a lot of questions that already cover the sorting issue. Have a look at them.

Regarding deletion:

You can iterate over the array and only add the values you want to keep to a new array:

var filtered = [];

for(var i = 0, l = myArray.length; i < l; i++) {
    if(myArray[i][3] !== 0) {
        filtered.push(myArray[i]);
    }
}

If you want to change the array in-place, you can use .splice()[docs]:

for(var i = myArray.length; i--; ) {
    if(myArray[i][3] === 0) {
        myArray.splice(i, 1);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消