Skip to content

How to filter an array with another array?

In this article, I would like to share with you some of the ways to filter array with another array. Below are some methods that I have learnt.

  • filter()
  • forEach()

Let’s take the below array for our learning,

let array1 = ["Boo", "Foo", "Zoo", "Doo", "Poo", "Noo"];
let array2 = ["Zoo", "Poo", "Loo", "Hoo"];
let filArray1 = [];
let filArray2 = [];

1. filter()

One of my favorite methods. We are taking advantage of the .filter method provided by the Array.prototype. The method is returning a new array with all the elements that pass a specific test(written by us).

filArray1 = array1.filter(function(item) {
  return !array2.includes(item); 
});
filArray2 = array2.filter(function(item) {
  return !array1.includes(item); 
});
console.log(filArray1);//["Boo", "Foo", "Doo", "Noo"];
console.log(filArray2);//["Loo", "Hoo"];

You can use indexOf() method also to check the array1 value is exists in array2 like below,

filArray1 = array1.filter(function(item) {
  return array2.indexOf(char) === -1;
});

In Next Version Of JavaScript ES6, It is even cleaner when you use the arrow function (=>).

filArray1 = array1.filter(arr => !array1.includes(item));

2. forEach

The forEach() method executes a provided function once for each array element.

array1.forEach(e => {
	if(!array2.includes(e)){
		filArray1.push(e);
	}
});
console.log(filArray1);//["Boo", "Foo", "Doo", "Noo"];
See also  How to represent negative infinity in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.