JavaScript - filtering array with an array

We are required to write a JavaScript function that takes in two arrays of literals. Our function should return a filtered version of the first array that contains all those elements that are present in that very array but not the second array.

We will use the Array.prototype.filter() function and check for the elements in the second array using the Array.prototype.includes() method.


The code for this will be −

const arr1 = [1,2,3,4,5];
const arr2 = [1,3,5];
const filterUnwanted = (arr1 = [], arr2 = []) => {
   let filtered = [];
   filtered = arr1.filter(el => {
      const index = arr2.indexOf(el);
      // index -1 means element is not present in the second array
      return index === -1;
   return filtered;
console.log(filterUnwanted(arr1, arr2));


And the output in the console will be −

[2, 4]