Ever needed to find or locate a specific array item? Luckily for us, we have a JavaScript method that can handle that task with ease. In this quick guide, I’ll go over the find()
JavaScript array method. If you’re ready, let’s get into it!
Lets start with the MDN documentation:
MDN – find()
The find()
method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
According to the documentation, it looks like find()
returns the first instance of our logic that is truthy. Let’s checkout some examples.
Consider the following array:
const numbers = [10, 20, 30, 40, 50]
Let’s say we wanted to find the first value in this array that is greater than 25. We can do that pretty simply by writing the following:
numbers.find(num => num > 25)
This will return the very first item that is greater than 25. So 30
will be returned. This method can also find strings! Check this out:
const users = ['Alex', 'Taylor', 'Jamie'] console.log( users.find(user => user === 'Taylor') ); //expected output: 'Taylor'
As you can see, this is a pretty easy method to use and can help you locate specific array items easily. Typically you’ll also want to pair this with the indexOf
method or use the index
parameter you have access to to retrieve the index of the returned array item. I’ll show an example below of both but if you’d like to learn more about the indexOf
array method, I’ll link below some resources.
JavaScript Basic Array Methods – Blog
JavaScript Basic Array Methods – Video
Consider the following array:
const students = ['Brian', 'Rohald', 'Travis']
Let’s say we wanted to find out if “Rohald” is a student and if so, we want to get back the array index that his name falls into. We can write the following:
const selectedStudent = students.find(student => student === 'Rohald');
console.log(students.indexOf(selectedStudent)) //expected output: 1
Now, here is the same example but using the index
parameter:
const students = ['Brian', 'Rohald', 'Travis'] const selectedStudent = students.find((student, index) => { if (student === 'Travis') { console.log(index) }
})
Awesome, now you should know how to use the find()
method in your projects. I hope you can feel comfortable using this method going forward because it will surely speed up your workflow!
Until next time, have fun and happy coding!