Question

I have an array of arrays in JS

eg array[ array['1','2','3','0'], array['2','3','4','1'], array['3','4','5','0'], ]

The innerarray has many elements and one of the elements is set for its deleted value of either '1' for deleted or '0' for not deleted.

In the array above it would be element 3 of the innerarray, so the middle element of the outerarray is set to be deleted.

After I have updated the mysql db via an ajax call I want to remove from the outerarray all elements that are set as deleted in the innerarray.

how do I remove from the outerarray according to the value of an element in the innerarray?

I have tried a for loop but doesnt seem to be working

  for(var i=0;i<outerarry.length;i++){
      if(outerarray[i][3]=='1'){
        outerarray.splice(i,1);
      }
   }

any ideas?

Was it helpful?

Solution

Iterate through the array in reverse so that the array does not reindex with each splice.

var arr = [['1','2','3','0'],['2','3','4','1'],['3','4','5','0'],['4','4','5','1'],['5','4','5','0'],['6','4','5','1'],['7','4','5','0']];

var arrLength = arr.length;
while(arrLength--){
    if(arr[arrLength][3] == 1){
       arr.splice(arrLength,1);
    }
}
console.log(arr);

JS Fiddle: http://jsfiddle.net/L5T9k/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top