The filter() method

The filter() method creates a new array containing only the elements of a given array which pass a test defined by the programmer.

For example:

const arr = ['Mike', 'John', 'Mehul', 'Rahul', 'Akshay', 'Deep','Om', 'Ryan'];const namesWithOnly4Letters = arr.filter( name => name.length == 4 );console.log(namesWithOnly4Letters);

The output is:

["Mike", "John", "Deep", "Ryan"]

As you can see, in the filter our supplied function always returns a Boolean. Whenever the inside function returns true, that particular element is included in namesWithOnly4Letters. Whenever it returns false, it is not.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.