Home > front end >  using splice inside 2D Array in Javascript
using splice inside 2D Array in Javascript

Time:07-05

I've created this 2D array, and I'm trying to delete the rows that are having 5 "ones" or more, I tried it with splice (a.splice(j,1)) but it doesn't work . I think because when using this method it changes the whole quantity of rows and that's affects the for loops.

Is it because I don't use splice correctly or should I use different method ?

Thanks !

a = Array(7).fill(0).map(x => Array(10).fill(0))

for (let i = 0; i < 5; i  ) {
  a[1][i   2] = 1;
  a[4][i   2] = 1;
  a[5][i   2] = 1;
}

console.log(a);


let count = 0;
for (let j = 0; j < 7; j  ) {
  for (let i = 0; i < 10; i  ) {
    if (a[j][i] == 1) {
      count = count   1;
    }
  }
  if (count > 4) {
    console.log("Line"   j);
    // a.splice(j,1);
  }
  count = 0;
  // a.splice(j,1);
}

CodePudding user response:

Your splice is correct but you move forward through the array (j is incremented). To do this type of operation you need to move backward through the array (j is decremented) - this way the changing array indices don't intefere with your loop.

See the example below:

a = Array(7).fill(0).map(x => Array(10).fill(0))

for (let i=0; i<5; i  ) {
  a[1][i 2] = 1;
  a[4][i 2] = 1;
  a[5][i 2] = 1;
}

console.log("Original array");
console.log(a);

for (let j = a.length - 1; j > 0; j--) {
  var count;
  
  for (let i = 0; i < a[j].length; i  ) {
    if (a[j][i] === 1) {
      count  = 1
    }
  }
  
  if (count > 4) {
    a.splice(j, 1);
  }
  
  count = 0;
}

console.log("Filtered array");
console.log(a);

  • Related