'filter' vs 'find': JavaScript array methods

'filter' vs 'find': JavaScript array methods

ยท

1 min read

ES6 ships with several array methods which enable one to perform operations such as

  1. Filtering values (filter)
  2. Summing up array elements (reduce)
  3. Performing the same operation for each element (map)

Assuming you want to find a single value given a condition, you'd most likely use find. But if you always use (filter, map and reduce) above others, it's time to re-learn find.

Some code to illustrate

We have an array of users

const users = [
  {
    name: "Alice",
    age: 19,
    id: 1
  },
  {
    name: "Bob",
    age: 24,
    id: 2
  },
]

We need a user with an id of 2

Getting the user using filter

const user = users.filter((user) => user.id === 2)
// returns [{name: "Bob", age: 24, id: 2}]
// to resolve, we do
const user = users.filter((user) => user.id === 2)[0]
// which then returns {name: "Bob", age: 24, id: 2}

Getting the user using find

const user = users.find((user) => user.id === 2)
// returns {name: "Bob", age: 24, id: 2}

There you have it. You've relearned the find array method.

ย