ES6 ships with several array methods which enable one to perform operations such as
- Filtering values (filter)
- Summing up array elements (reduce)
- 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.
Top comments (0)