DEV Community

Osinachi Chukwujama
Osinachi Chukwujama

Posted on

1 1

'filter' vs 'find': JavaScript array methods

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
  },
]
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Getting the user using find

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

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay