ComparisonComparisons

find() vs filter()

find() returns the first element that matches a condition, or undefined, while filter() returns a new array with every element that passed the test.

On this page

Side-by-side comparison

#

Example

#
JavaScript
const users = [
  { id: 1, name: 'Emma', active: true },
  { id: 2, name: 'Jack', active: false },
  { id: 3, name: 'Mia', active: true }
]

const oneUser = users.find((user) => user.active)
const activeUsers = users.filter((user) => user.active)

console.log(oneUser)
console.log(activeUsers)
Console
{ id: 1, name: 'Emma', active: true }
[{ id: 1, name: 'Emma', active: true }, { id: 3, name: 'Mia', active: true }]

Definition and usage

#

Both methods check the arrayโ€™s elements with the same testing function (element, index, array) and donโ€™t change the original. They differ in what they do with the test result: find() stops at the first element for which the function returns a truthy value, while filter() checks every element and collects the matches into a new array.

find() returns the element itself, or undefined when none matches. filter() always returns an array, even an empty [], so you can immediately map the result further or count it with .length. Because find() finishes its work at the first match, it can be faster on large arrays than filter(), which always goes through every element.

The choice depends on how many elements you need. Looking for one specific record, for example a user by id? Use find(). Need a list of elements that match a condition, for example active users to display? Use filter().

Syntax

#
Syntax
array.find(callbackFn)
array.filter(callbackFn)

More examples

#
Safe reading after find()
JavaScript
const products = [
  { slug: 'html', price: 0 },
  { slug: 'react', price: 199 }
]

const missing = products.find((product) => product.slug === 'vue')
const free = products.filter((product) => product.price === 0)

console.log(missing)
console.log(free.length)
console.log(missing?.price ?? 'No product')
Console
undefined
1
No product
find() checks fewer elements than filter()
JavaScript
const numbers = [1, 2, 3, 4, 5]

const checkedByFind = []
numbers.find((number) => {
  checkedByFind.push(number)
  return number > 2
})

const checkedByFilter = []
numbers.filter((number) => {
  checkedByFilter.push(number)
  return number > 2
})

console.log(checkedByFind)
console.log(checkedByFilter)
Console
[1, 2, 3]
[1, 2, 3, 4, 5]

find() stops once it hits 3 and no longer checks 4 and 5. filter() always goes through the whole array.

Good practices

#
  • The result of find() can be undefined. Guard reading its properties with the ?. operator.
  • Only checking whether an element exists, without needing to use it? some() is clearer than comparing the result of find() to undefined.
  • When you need the position of the matching element, not its value, use findIndex().

Related entries

#

Spotted a mistake or missing an example? Write to us.