Sometimes, we want to filter a JavaScript array from all elements of another JavaScript array.
In this article, we’ll look at how to filter a JavaScript array from all elements of another array.
Using the Array.prototype.filter Method
We can use the JavaScript array filter
method to filter out the array entries that are entries of another array.
For instance, we can write:
const filtered = [1, 2, 3, 4].filter(
function(e) {
return this.indexOf(e) < 0;
},
[2, 4]
);
console.log(filtered);
to do so.
We call filter
on [1, 2, 3, 4]
with a callback that calls this.indexOf(e) < 0
and return the result.
We set the value of this
in the callback with the 2nd argument of filter
.
Therefore, this
is [2, 4]
.
And so filtered
is [1, 3]
.
We cam also use the includes
method to filter out the items that are in the other array.
For instance, we can write:
const filtered = [1, 2, 3, 4].filter(
function(e) {
return !this.includes(e);
},
[2, 4]
);
console.log(filtered);
And we get the same result for filter
.
We can replace the callback with an array function if we don’t use this
inside the callback.
To do this, we can write:
const filtered = [1, 2, 3, 4].filter(
(e) => {
return [2, 4].indexOf(e) < 0;
}
);
console.log(filtered);
or:
const filtered = [1, 2, 3, 4].filter(
(e) => {
return ![2, 4].includes(e);
}
);
console.log(filtered);
We replace this
with the array itself.
And we get the same result.
Conclusion
We can use the JavaScript array filter
instance method to return an array that has the items that are included in another array filtered out.