Find Index of particular element in array JavaScript

In this article, we will learn how to get the index of an element in an array in a javascript array on its value.
Let's say we have an array that contains different values of items and we have to find the index of a particular element in that array.
const birds = ['pigeon', 'crow', 'sparrow', 'duck', 'parrot'];
So how do we get the index of an item?
If the items in the array are primitive data types like string, number, or boolean, then we can use the indexOf() method in Javascript.
The indexOf()
method in javascript returns the first index of a specific value when it is found in an array. And if the item is not found in the array it returns -1
.
Syntax:
array.indexOf(item)
item : the value we are searching for in the array.
Let's see an example:
const birds = ['pigeon', 'crow', 'sparrow', 'duck', 'parrot'];
console.log(birds.indexOf('sparrow')) // 2
We get the index of the item 'sparrow' i.e 2 .
Note: In an array, the index starts from 0 .
Now, let's say instead of primitive values, we have non-primitive values like an object.
Will this indexOf() method return us the index of the object item in an array? Let's find out.
Suppose, we have an array of objects.
Example:
const birds = [
{name:'pigeon'},
{name:'crow'},
{name:'sparrow'},
{name:'duck'},
{name:'parrot'}
];
console.log(birds.indexOf({name:'sparrow'})) // -1
As, you can see we get -1
as returned value, which implies that the item is not found in the array.
This is because objects are compared by reference whereas strings or numbers (primitive type) are compared by value.
Important Note:
Primitives are the immutable data type and their value cannot be changed after it is created. And primitives are compared by value. So two values are equal if they have the same value.
var num1 = 5; var num2 = 5; console.log(num1 === num2) //true
Non-primitives are the mutable data types and their value cannot be changed after it is created. And non-primitives are not compared by value. So two values can have the same value but they are not strictly equal.
var person1 = {name:'Jack'} var person2 = {name:'Jack'} console.log(person1 === person2) // false
So, how do we get the index of an item in an array of objects?
We can use the findIndex()
method in JavaScript the find index of an object.
The findIndex()
method returns the first item in an array that satisfies a given testing condition. If the element is not found it returns -1
.
For example:
const birds = [
{name:'pigeon'},
{name:'crow'},
{name:'sparrow'},
{name:'duck'},
{name:'parrot'}
];
const index = birds.findIndex((element, index) => {
if (element.name === 'sparrow') {
return true
}
})
console.log(index) // 2
Here, we have looped through each element of the array along with its index and when the condition i.e element.name === 'sparrow'
is matched, it returns us the index of the object in the array. Here the index is 2 .