我们可以使用filter
函数从数组中筛选出单个值,如下所示:
var possi = [
['1','2','3'], ['4','5','6'], ['7','8','9'], ['1','4','7'],
['2','5','8'], ['3','6','9'], ['1','5','9'], ['3','5','7']
];
var remove = '1';
possi = possi.filter(function(p){
return p.indexOf(remove) === -1;
});
结果是:
[ [ '4', '5', '6' ],
[ '7', '8', '9' ],
[ '2', '5', '8' ],
[ '3', '6', '9' ],
[ '3', '5', '7' ] ]
但是如果我们要移除多个元素,那就是:如果我们有:
var remove = ['1', '6'];
我们如何检查remove
中是否存在每个possi
元素,并过滤掉匹配的possi
元素?
另外,在这种情况下,map
或reduce
这样的其他任何功能都可以成为更好的解决方案吗?
答案 0 :(得分:4)
如果要删除possi
中与数组remove
的任何元素匹配的所有数组,可以将Array.prototype.filter()
与Array.prototype.some()
结合使用:
var possi = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['1', '4', '7'],
['2', '5', '8'],
['3', '6', '9'],
['1', '5', '9'],
['3', '5', '7']
];
var remove = ['1', '6'];
possi = possi.filter(function(p) {
return !p.some(function(v) {
return remove.indexOf(v) !== -1;
});
});
console.log(possi);

结果是:
[
['7', '8', '9'],
['2', '5', '8'],
['3', '5', '7']
]