Filter array with filter() and includes() in JavaScript


Let’s say following is our array −

const names = ['John', 'David', 'Mike','Sam','Carol','Bob'];

Now, we will filter the array −

var nameObject=names.filter((allNameObject) => !['David', 'Mike','Sam','Carol'].includes(allNameObject));

Example

const names = ['John', 'David', 'Mike','Sam','Carol','Bob'];
console.log("The names are=");
console.log(names);
var nameObject=names.filter((allNameObject) => !['David', 'Mike','Sam','Carol'].includes(allNameObject));
console.log("After filter=");
console.log(nameObject);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo65.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo65.js
The names are=
[ 'John', 'David', 'Mike', 'Sam', 'Carol', 'Bob' ]
After filter=
[ 'John', 'Bob' ]

Updated on: 03-Sep-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements