How to get the Index of an Item in a JavaScript Array

Updated onbyAlan Morel
How to get the Index of an Item in a JavaScript Array

Often times in JavaScript, you will have an array and an item but you don't know the index of the item.

In this post, we'll learn how to get the index of an item in an array.

Getting the index of a primitive in an array

If the item you're trying to get is a primitive, then you can use the built-in indexOf method.

This method takes the item you're looking for as an argument and returns the index of the item, when applied to the array.

Let's see an example:

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; const item = 3; const index = numbers.indexOf(item); // 2

Getting the index of an object in an array

When you have an object as your item, things are a little more complicated. This is because objects are not compared by values, but by reference.

What this means is that the item you are passing it will be different from the item in the array, meaning the index will be different.

In this situation, you're going to want to use the findIndex method.

The findIndex method takes a function as an argument and returns the index of the item that the function returns true for.

In other words, you are writing the code that determines when the item is the one you're looking for, and that function is being run on the entire array until it finds the item you're looking for.

Let's look at an example:

JAVASCRIPT
const numbers = [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 } ]; const item = { value: 3 }; const index = numbers.findIndex(number => number.value === item.value); console.log(index); // 2

Because on the third element (2nd index), that function returns true, it returned the index of the item, which was 2.

Conclusion

In this post, we saw how to get the index of an item in an array, both for when the item is a primitive and when the item is an object.

Hopefully, you've found this post helpful and enjoyed reading it.

Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.