我的数组如下所示:
var my_array=[
[[1,0], [2,2], [4,1]],
[[4,9], [3,1], [4,2]],
[[5,6], [1,5], [9,0]]
]
我想过滤上面的 my_array
并删除所有数组(例如 [[4,9], [3,1], [4,2]]
) 来自上面的数组 IF 数组的所有 子数组
在 1. 位置 (child array[1]
)
所以我的结果应该是这样的:
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.
我的想法是使用类似这样的代码,但我无法真正让它工作:
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))
最佳答案
简单的方法是使用 Array#some
在外部数组的 filter
中查找其中符合我们标准的任何数组,并使用 Array#includes
(或者在旧版浏览器上使用 Array#indexOf
,与 -1 进行比较表示未找到)在 find
回调中查看子数组是否包含 0
.
在 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;
}
或者在 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;
}
关于javascript - 在javascript中从多维数组中删除特殊元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495321/