我们可以使用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'];
如何检查possi
中是否存在每个remove
元素并过滤出匹配的possi
元素?
此外,在这种情况下,map
或reduce
等任何其他函数是更好的解决方案吗?
如果您想删除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']
]