(╯°□°)╯ .find()
find()
is used to find an element that returns true
depending on the condition we have.
const myArr = [1, 4, 6, 9]
const useFind = myArr.find(el => el === 4)
// 4
In the example above we use find()
to return the element thats ===
to 4.
However find()
returns the first element it finds.
const myArr = [1, 2, 3, 4, 5, 6]
const useFind = myArr.find(el => el > 2)
// 3
In this example we used a larger array and used find()
to return an element >
than 2. Even though the array contains more elements greater than 2 it still returned 3. This is because it returns the first element that is true
.
Finding Specific Values
find()
can be useful when you want a specific id from an array of objects.
const goodBoys = [
{name: 'spike'},
{name: 'winston'},
{name: 'scruffy'}
]
const findDog = goodBoys.find(el => el.name === 'spike')
// { name: 'spike' }
This time we use find()
to return us 'spike'.
Top comments (0)