How to get the Index of an Item in a JavaScript Array
Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue