如何在JavaScript中使用过滤器从多维数组中删除多个元素



我们可以使用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元素?

此外,在这种情况下,mapreduce等任何其他函数是更好的解决方案吗?

如果您想删除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']
]

相关内容

  • 没有找到相关文章

最新更新