0

I have a data structure like this:

var 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]
 ]
];

Specifically, I'm interested in whether the value of the second item in each inner-most array is 0 or not. If that value is zero, I want to remove the entire array that harbors that value.

Based on the conventional approach for removing things from arrays seen here: How can I remove a specific item from an array? I attempted the following:

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

However, this seemed to remove my whole data, as nothing even appeared in my console log -- not even undefined.

Question

How does one remove an entire array based on a condition?

Derek Wang
  • 9,675
  • 4
  • 14
  • 36
Arash Howaida
  • 2,235
  • 2
  • 13
  • 34

2 Answers2

1

You can do a map and filter the inner item based on the item in index 1

var 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]
 ]
];

console.log(data.map(item=>item.filter(x=>x[1]!=0)));
Guruparan Giritharan
  • 12,321
  • 4
  • 16
  • 35
1

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);
Derek Wang
  • 9,675
  • 4
  • 14
  • 36