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?

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.