Mc-Ac
Mc-Ac

Reputation: 161

Javascript, filtering array with an array

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?

Upvotes: 0

Views: 144

Answers (6)

Redu
Redu

Reputation: 26161

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

A much simpler way would be:

var filteredArray = array1.filter(function(item) {
    return !(array2.indexOf(item) >= 0);
});

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

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

Upvotes: 2

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

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

filteredArray = array1.filter(function (y) {
		return array2.indexOf(y) < 0;
	});
console.log(filteredArray);

Upvotes: 1

Sinan Guclu
Sinan Guclu

Reputation: 1087

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;

Upvotes: 0

Related Questions