简体   繁体   中英

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 (eg [[4,9], [3,1], [4,2]] ) from the array above IF all child arrays of the array have no specific value (eg 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)) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM