JavaScript, how to filter an array
By Flavio Copes
Learn how to filter an array in JavaScript using the built-in filter() method with a callback, which returns a new array containing only the items that match.
You have an array, and you want to filter it to get a new array with just some of the values of the original array.
How can you do so?
JavaScript arrays come with a built-in filter() method that we can use for this task.
filter() accepts a callback function. It calls that function once for every item in the array. If the callback returns true, the item goes into the new array. If it returns false, the item is left out.
Here is the simplest example, keeping only the even numbers:
const numbers = [1, 2, 3, 4, 5, 6]
const even = numbers.filter((number) => number % 2 === 0)
console.log(even) // [ 2, 4, 6 ]
Filtering an array of objects
Most of the time you filter arrays of objects. Say we have an array with 4 objects representing 4 dogs:
const dogs = [
{
name: 'Roger',
gender: 'male'
},
{
name: 'Syd',
gender: 'male'
},
{
name: 'Vanille',
gender: 'female'
},
{
name: 'Luna',
gender: 'female'
}
]
and you want to filter the male dogs only.
You can do so in this way:
const maleDogs = dogs.filter((dog) => dog.gender === 'male')
// [ { name: 'Roger', gender: 'male' }, { name: 'Syd', gender: 'male' } ]
The callback receives each dog in turn. We return the result of the comparison dog.gender === 'male', which is already a boolean, so there’s no need for an if.
Does filter() change the original array?
No. filter() returns a brand new array and leaves the original untouched:
console.log(dogs.length) // 4
console.log(maleDogs.length) // 2
This is useful because you often want to keep the original data around, for example to apply a different filter later.
If no item passes the test, you get back an empty array, not undefined or null. You can safely call array methods on the result without checking it first.
A common pitfall
A mistake I see often is using filter() to look up one single item:
const roger = dogs.filter((dog) => dog.name === 'Roger')
This works, but you get back an array with one item inside. To use the dog you’d have to write roger[0], and it’s easy to forget that.
When you expect a single result, use find() instead:
const roger = dogs.find((dog) => dog.name === 'Roger')
// { name: 'Roger', gender: 'male' }
find() returns the first matching item directly, or undefined if nothing matches.
Related posts about js: