filter method to filter an array in JavaScript

Let's now explore the very useful filter method to filter the elements of an array. Like the methods we have already studied, this method gets a callback function in the parameter (with the same parameters as the map and forEach methods), which will be executed for each array element.

As a result, filter returns a new array, which will include only those elements for which the callback returns true.

Let's see how the function works with an example. Let's say we have an array of numbers:

let arr = [1, 2, 3, 4, 5];

Let's filter the array, leaving only even numbers in it:

let arr = [1, 2, 3, 4, 5]; let result = arr.filter(function(elem) { if (elem % 2 == 0) { return true; } else { return false; } }); console.log(result); // shows [2, 4]

Let's simplify the code using logical operators:

let arr = [1, 2, 3, 4, 5]; let result = arr.filter(function(elem) { return elem % 2 == 0; }); console.log(result); // shows [2, 4]

Let's simplify the code even more using arrow functions:

let arr = [1, 2, 3, 4, 5]; let result = arr.filter(elem => elem % 2 == 0); console.log(result); // shows [2, 4]

This solution is so short that it can be placed in the parameter of console.log:

let arr = [1, 2, 3, 4, 5]; console.log( arr.filter(elem => elem % 2 == 0) );

Given an array of numbers. Leave only positive numbers in it.

Given an array of numbers. Leave only negative numbers in it.

Given an array of numbers. Leave in it only numbers that are greater than zero, but less than 10.

Given an array with strings. Leave in it only those strings whose length is more than 5 characters.

Given an array of numbers. Leave in it only those numbers whose product of their values and index numbers is less than 30.

An array is given, it can contain ordinary elements and subarrays, for example [1, 2, [3, 4], 5, [6, 7]]. Leave only ordinary elements in it.

One more usage

Let us again have our array:

let arr = [1, 2, 3, 4, 5];

Let's count the number of even elements in it:

let arr = [1, 2, 3, 4, 5]; let filtered = arr.filter(elem => elem % 2 == 0); console.log( filtered.length ); // shows 2

Let's rewrite it even easier:

let arr = [1, 2, 3, 4, 5]; console.log( arr.filter(elem => elem % 2 == 0).length );

Given an array of numbers. Count the number of negative numbers in this array.

enru