0

I need to filter an array1, with each element in my array 2. Both arrays can have a random number of elements.

 array1 = [1,2,3,4,5];
 array2 = [1,3,5];
 filteredArray = [];

 array2.forEach(function(x){
   filteredArray = array1.filter(function(y){
     return y !== x;
   });
 });
 return filteredArray;
 //should return -> [2,4]
 // returns [1,2,3,4]

How can I filter an array with all elements in another array?

Mc-Ac
  • 161
  • 1
  • 8
  • http://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value - you can use this – RaV Jul 27 '16 at 14:11

6 Answers6

2

use arrays indexOf method

var array1 = [1,2,3,4,5];
var array2 = [1,3,5];
var filteredArray = array1.filter(function(x) {
    return array2.indexOf(x) < 0;
});

or, for sexy people, use !~ with indexOf

var array1 = [1,2,3,4,5];
var array2 = [1,3,5];
var filteredArray = array1.filter(function(x) {
    return !~array2.indexOf(x);
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

A much simpler way would be:

var filteredArray = array1.filter(function(item) {
    return !(array2.indexOf(item) >= 0);
});
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
1

array1 = [1, 2, 3, 4, 5];
array2 = [1, 3, 5];
filteredArray = [];

filteredArray = array1.filter(function (y) {
  return array2.indexOf(y) < 0;
 });
console.log(filteredArray);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
0

You can use indexOf() to check if the array2 item is in array1 then only add it to filteredArray if it is:

 array1 = [1,2,3,4,5];
 array2 = [1,3,5];
 filteredArray = [];

 array2.forEach(function(x){
     if (array1.indexOf(array2[x] > -1) {
         filteredArray.push(array2[x]);
     }
 });
 return filteredArray;
Sinan Guclu
  • 1,075
  • 6
  • 16
0

In ES6, you could use Set for it.

var array1 = [1, 2, 3, 4, 5],
    array2 = [1, 3, 5],
    filteredArray = array1.filter((set => a => !set.has(a))(new Set(array2)));

console.log(filteredArray);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • We can make it even more convoluted..! How about `filteredArray = array1.filter(function(set,a) {return !set.has(a)}.bind(null,new Set(array2)));`..? – Redu Jul 27 '16 at 15:16
  • in this case, you could use `new Set(...)` as this args. – Nina Scholz Jul 27 '16 at 15:18
0

All indexOf no play makes me a dull boy...

var array1 = [1,2,3,4,5],
    array2 = [1,3,5],
  filtered = array1.filter(e => !array2.includes(e));
console.log(filtered);
Redu
  • 25,060
  • 6
  • 56
  • 76