Placid
Placid

Reputation: 1448

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?

Upvotes: 0

Views: 568

Answers (1)

Matthias A. Eckhart
Matthias A. Eckhart

Reputation: 5156

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

Upvotes: 4

Related Questions