Filtering Items From an Array in JavaScript

The first argument is a callback that receives the current element of the array, in the callback you insert your code to decide if the cur

cover for Filtering Items From an Array in JavaScript



Syntax

filter((element, index, array) => ...)
  • element is the current element the callback will receive.
  • index (optional) is the index of the current element.
  • array (optional) is the array where the filter method is being applied.

How to use the filter method

This method is pretty simple, the array will be looped and the elements that fall under a certain criteria will be in the filtered array. The first argument of the filter element is a callback that receives the current element of the array, in the callback you insert your code to decide if the current element should be in the final array, if the conditional is truth, the element will be in the new array.

For example, consider the following array of objects containing data of cities:

const cities = [{ name: 'Porto Alegre', country: 'Brazil'}, { name: 'Paris', country: 'France'}, { name: 'Lisbon', country: 'Portugal'}, { name: 'Eldorado do Sul', country: 'Brazil'} ]

To select just the cities in Brazil, we can use the following code:

const brazilCities = cities.filter(currentCity => currentCity.country === 'Brazil')

The result will be the objects with the cities Porto Alegre and Eldorado do Sul.