Jonas0000
Jonas0000

Reputation: 1113

Remove special elements from multidimensional array in javascript

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

Upvotes: 0

Views: 56

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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

Upvotes: 1

Related Questions