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 Express
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
Getting Started with Deno
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
