简体   繁体   中英

How to remove multiple elements from multidimensional array with filter in JavaScript?

We can filter out a single value from an array with the filter function like this:

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;
});

The result is:

[ [ '4', '5', '6' ],
  [ '7', '8', '9' ],
  [ '2', '5', '8' ],
  [ '3', '6', '9' ],
  [ '3', '5', '7' ] ]

But if we have multiple elements to remove, that is, if we have:

var remove = ['1', '6'];

How can we check if each remove element exists in possi and filter out the matching possi element?

Also, do any other functions such as map or reduce be a better solution in this case?

If you want to remove all arrays in possi which match any element of array remove , you could combine Array.prototype.filter() with 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); 

The result is:

[
  ['7', '8', '9'],
  ['2', '5', '8'],
  ['3', '5', '7']
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM