[英]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]
) 我想过滤上面的my_array
并从上面的数组中删除所有数组(例如[[4,9], [3,1], [4,2]]
),如果该数组的所有child arrays
数组都没有特定值(例如0
)位于1.位置( 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 a0
-column at the first index. 参见上文:从my_array
删除第二个数组,因为第二个子数组在第一个索引处不包括0
列。
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
. 一种简单的方法是在外部数组的filter
使用Array#some
查找匹配我们条件的任何数组,并使用Array#includes
(或在较旧的浏览器中为Array#indexOf
,与未找到的-1比较)在find
回调中查看子数组是否包含0
。
In ES2015+ 在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: 或在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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.