JavaScript Array filter: Filtering Elements

Created with Sketch.

JavaScript Array filter: Filtering Elements

Summary: in this tutorial, you will learn how to use the JavaScript Array filter() method to filter elements in an array.

Introduction to JavaScript array filter() method

One of the most common tasks when working with an array is to create a new array that contains a subset of elements of the original array.

Suppose you have an array of city objects where each object contains two properties: name and population.

let cities = [
{name: 'Los Angeles', population: 3792621},
{name: 'New York', population: 8175133},
{name: 'Chicago', population: 2695598},
{name: 'Houston', population: 2099451},
{name: 'Philadelphia', population: 1526006}
];

Code language: JavaScript (javascript)

To find the city whose population is greater than 3 million, you typically loop over the array elements using a for loop and test if the value of the population property satisfies the condition, like this:

let bigCities = [];
for (let i = 0; i < cities.length; i++) {
if (cities[i].population > 3000000) {
bigCities.push(cities[i]);
}
}
console.log(bigCities);

Code language: JavaScript (javascript)

Output:

[
{ name: 'Los Angeles', population: 3792621 },
{ name: 'New York', population: 8175133 }
]

Code language: JavaScript (javascript)

JavaScript Array provides the filter() method that allows you to do this task in a shorter and cleaner way.

The following example returns the same result as the example above:

let bigCities = cities.filter(function (e) {
return e.population > 3000000;
});
console.log(bigCities);

Code language: JavaScript (javascript)

In this example, we call the filter() method of the cities array object and pass a function that tests each element.

Inside the function, we check if the population of each city in the array is greater than 3 million. If it is the case, the function returns true or false otherwise.

The filter() method includes the only elements in the result array if they satisfy the test in the callback function.

Starting with ES6, you can use the arrow function to make it more concise:

let bigCities = cities.filter(city => city.population > 3000000);

console.log(bigCities);

Code language: JavaScript (javascript)

JavaScript Array filter() method in detail

The following illustrates the syntax of the filter() method:

arrayObject.filter(callback, contextObject);

Code language: CSS (css)

The filter() method creates a new array with all the elements that pass the test implemented by the callback() function.

Internally, the filter() method iterates over each element of the array and passes each element to the callback function. If the callback function returns true, it includes the element in the return array.

The filter() method accepts two named arguments: a callback function and an optional object.

Like other iterative methods of the Array object such as every(), some(), map() and forEach(), the callback function has the following form:

function callback(currentElement, index, array){
// ...
}

Code language: JavaScript (javascript)

The callback function takes three arguments:

  • The currentElement argument is the current element in the array that is being processed by the callback function.
  • The index of the currentElement that is being processed by the callback function.
  • The array object being traversed.

The index and array arguments are optional.

The contexObject argument of the filter() method is optional. If you pass the this value, you can reference it by using this keyword inside the callback function.

It is important to note that the filter() method does not change the original array.

More JavaScript Array filter() method examples

Because the filter() method returns a new array, you can chain the result with other array methods such as sort() and map().

For example, the following illustrates how to chain the three methods: filter(),sort(), and map():

cities
.filter(city => city.population < 3000000)
.sort((c1, c2) => c1.population - c2.population)
.map(city => console.log(city.name + ':' + city.population));

Code language: JavaScript (javascript)

Output:

Philadelphia:1526006
Houston:2099451
Chicago:2695598

Code language: CSS (css)

How it works.

  • First, filter the cities whose populations are less than 3 million using the filter() method.
  • Second, sort the resulting cities by the populations in descending order using the sort() method.
  • Third, output array element to the console using the map() method.

The following example illustrates the use of the contextObject argument that specifies an object which can be referenced in the callback() function using the this keyword

function isInRange(value) {
if (typeof value !== 'number') {
return false;
}
return value >= this.lower && value <= this.upper;
}

let data = [10, 20, "30", 1, 5, 'JavaScript filter', undefined, 'example'];

let range = {
lower: 1,
upper: 10
};

let numberInRange = data.filter(isInRange, range);

console.log(numberInRange); // [10, 1, 5]

Code language: JavaScript (javascript)

Output:

[ 10, 1, 5 ]

Code language: JSON / JSON with Comments (json)

How it works.

  • First, define the isInRange() function that checks if its argument is a number and in the range specified by the lower and upper properties of an object.
  • Next, define an array of mixed data that contains numbers, strings, and undefined.
  • Then, define the range object with two properties lower and upper.
  • After that, call the filter() methods of the data array and pass in the isInRange() function and the range object. Because we pass in the range object, inside the isInRange() function, the this keyword references to the range object.
  • Finally, show the result array in the console.

In this tutorial, you have learned how to use the JavaScript Array filter() method to filter elements in an array based on a test provided by a callback function.

Leave a Reply

Your email address will not be published. Required fields are marked *