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

时间:2015-09-08 11:33:58

标签: javascript arrays multidimensional-array

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

另外,在这种情况下,mapreduce这样的其他任何功能都可以成为更好的解决方案吗?

1 个答案:

答案 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']
]