filter vs. find: JavaScript array methods

Filter vs Find

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

  1. Filtering values (filter)
  2. Summing up array elements (reduce)
  3. Performing the same operation on 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 the methods mentioned above (filter, map and reduce), it’s time to re-learn find.

A coding example

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 users = [
{
name: "Alice",
age: 19,
id: 1
},
{
name: "Bob",
age: 24,
id: 2
},
]
let user = users.filter((user) => user.id === 2);
console.log(user);

However, the code above returns [{name: "Bob", age: 24, id: 2}]. So, what we need is being returned inside an array.

To resolve this, we simply​ do the following:

const users = [
{
name: "Alice",
age: 19,
id: 1
},
{
name: "Bob",
age: 24,
id: 2
},
]
user = users.filter((user) => user.id === 2)[0];
console.log(user);
// which then returns {name: "Bob", age: 24, id: 2}

Getting the user using find

const users = [
{
name: "Alice",
age: 19,
id: 1
},
{
name: "Bob",
age: 24,
id: 2
},
]
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.

find returns the first matching element and filter returns an array of all matching elements.

Free Resources