js – remove array from nested arrays upon condition

Your code will throw an error thisArray is undefined because

  • Inside variable k loop, you have removed the item on data[j] variable if it matches the condition. So the length of data[j] will be decreased once you remove the item from data[j].
  • And you have looped k from 0 ~ 3, so if one item is removed from data[j], its’ length will be 3 (it means data[j][2] will be undefined.)

So you will get that error. It is needed to include the handler for undefined error part as follows.

const data = [
 [
   [0,0,4],
   [0,1,4],
   [0,0,4],
   [0,0,4]
 ],

 [
   [0,1,4],
   [0,1,4],
   [0,0,4],
   [0,1,4]
 ],

 [
   [0,0,4],
   [0,0,4],
   [0,1,4],
   [0,1,4]
 ]
];

for (var j = 0; j < 3; j++) {
  for (var k = 0; k < 4; k++) {
      var thisArray = data[j][k];
      if (thisArray && thisArray[1] == 0) {
        data[j].splice(k,1);
        k --;
      }
  }
}
console.log(data);

Or simply, it can be done using Array.map and Array.filter.

const data = [
 [
   [0,0,4],
   [0,1,4],
   [0,0,4],
   [0,0,4]
 ],

 [
   [0,1,4],
   [0,1,4],
   [0,0,4],
   [0,1,4]
 ],

 [
   [0,0,4],
   [0,0,4],
   [0,1,4],
   [0,1,4]
 ]
];

const output = data.map((item) => item.filter(subItem => subItem[1]));
console.log(output);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top