Anshuman Bhardwaj
The Sane Developer's Blog

The Sane Developer's Blog

4 ways of finding elements in a JavaScript Array

4 ways of finding elements in a JavaScript Array

Anshuman Bhardwaj's photo
Anshuman Bhardwaj
·Feb 21, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Arrays are the building blocks for data-based web apps. We can store and manipulate data using an Array easily.

Today, we are going to see 4 ways to find an element in an Array, along with some use cases explained with examples.

I know, I know...


find

the find method returns the first item that returns true for the passed callback condition, otherwise returns undefined if all items return false for the callback condition.

const numbers = [1, 3, 4, 6, 10];

numbers.find(element => element > 6); // 10

numbers.find(element => element > 10); // undefined

findIndex

the findIndex method returns the index of the first item that returns true for the passed callback condition, otherwise returns -1 if all items return false for the callback condition.

const numbers = [1, 3, 4, 6, 10];

numbers.findIndex(element => element > 6); // 4

numbers.findIndex(element => element > 10); // -1

The find methods are useful when you don't know exactly what you're looking for. But, you know a way to identify it.


indexOf

the indexOf method returns the index of the first item that matches the passed element, otherwise returns -1.

const numbers = [1, 3, 4, 6, 10];

numbers.indexOf(10); // 4

numbers.indexOf(16); // -1

The indexOf uses the same comparison logic as ===


lastIndexOf

the lastIndexOf methods similar to indexOf we saw above, the only difference being it starts the look up from the tail end of the array.

So, it's a good idea to use lastIndexOf if you know that the element has a higher chance of being in the latter half.

const numbers = [1, 3, 4, 6, 10];

numbers.lastIndexOf(10); // 4

numbers.lastIndexOf(16); // -1

The indexOf methods are useful when you know exactly what you're looking for.


Summary

To summarise, I would suggest using

  • find, when you don't know what you're looking for but you know how it should look.
  • findIndex, to get the index of the element.
  • indexOf, when you know exactly what you're looking for, and want the index of the element.
  • lastIndexOf, when you know what you're looking for, you know it's somewhere at the end, and want the index of the element.

That's it for now. I hope you find this article helpful! Should you have any feedback or questions, please feel free to put them in the comments below.

For more such articles, please follow me on Twitter

Until next time


Resources

MDN docs

Did you find this article valuable?

Support Anshuman Bhardwaj by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this