我有一个这样的整数数组:
var items = [
[1, 1, 2, 4],
[2, 1, 4, 6],
[5, 6, 4, 1],
[1, 6, 3, 1]
];
有没有一种简单的方法来查找和删除在定义位置具有特定值的所有数组? 例如,如果我想删除所有在第二个位置带有 '1' 的数组,结果应该是:
var items = [
[5, 6, 4, 1],
[1, 6, 3, 1]
];
如果我删除所有第三个位置的“4”,结果应该是:
var items = [
[1, 1, 2, 4],
[1, 6, 3, 1]
];
我知道我可以通过循环遍历所有元素来做到这一点,但是当二维数组很大(>1000 个数组)时,这似乎需要很长时间。
最佳答案
遍历items
,使用Array#filter函数过滤那些在给定位置没有给定值的内部数组。
function filterByPosition(array, number, position) {
return array.filter(innerArray => innerArray[position - 1] !== number);
}
const items = [
[1, 1, 2, 4],
[2, 1, 4, 6],
[5, 6, 4, 1],
[1, 6, 3, 1]
];
const newItems1 = filterByPosition(items, 1, 2);
console.log('Items1:', newItems1);
const newItems2 = filterByPosition(items, 4, 3);
console.log('Items2:', newItems2);
关于javascript - 在Javascript中过滤二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021977/