ES6 ships with several array methods that enable one to perform operations such as:
filter
)reduce
)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
.
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
.
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}
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 andfilter
returns an array of all matching elements.