0

My array looks like this:

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
]

I'd like to filter the my_array above and remove all arrays (e.g. [[4,9], [3,1], [4,2]]) from the array above IF all child arrays of the array have no specific value (e.g. 0) at the 1. position (child array[1])

So my result should look like this:

var result_array=[
  [[1,0], [2,0], [4,1]],
  [[5,6], [1,5], [9,0]]
]

See above: Remove second array from my_array because the second child arrays do not include a 0-column at the first index.

My idea was to use something like this code, but I can not really get it working:

var my_array=[
    [[1,0], [2,2], [4,1]],
    [[4,9], [3,1], [4,2]],
    [[5,6], [1,5], [9,0]]
]
  
 result_array = my_array.filter(function(item){ return item[1] != 0 })
console.log(JSON.stringify(result_array))

2
  • What do you call child arrays? Commented Nov 26, 2017 at 11:02
  • e.g [4,9] this one! Commented Nov 26, 2017 at 11:03

1 Answer 1

1

The simple way would be to use Array#some in the filter on the outer array to find any array in it matching our criterion, and to use Array#includes (or Array#indexOf on older browsers, comparing with -1 for not found) in the find callback to see if the child array contains 0.

In ES2015+

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
];
var filtered = my_array.filter(middle => middle.some(inner => inner.includes(0)));
console.log(filtered);
.as-console-wrapper {
  max-height: 100% !important;
}

Or in ES5:

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
];
var filtered = my_array.filter(function(middle) {
  return middle.some(function(inner) {
    return inner.indexOf(0) != -1;
  });
});
console.log(filtered);
.as-console-wrapper {
  max-height: 100% !important;
}

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

3 Comments

Ooops, if you see Array#find above, hit refresh. Should be #some.
Think OP wants position specific test in middle arrays
@charlietfl: Thanks, but apparently not, as OP has accepted an answer using exactly my code, posted well after my answer.

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.