Open In App

JavaScript indexOf() method in an Object Array

In JavaScript, indexOf() methods provide the first index at which the given element exists, and -1 in case it is not present in the array.

Syntax:

indexOf(element)
indexOf(element, start);

Parameters:

Return value:

JavaScript indexOf() method returns the value of the index at which the element is present, and -1 when the element doesn't exist.

JavaScript indexOf() method in an Object Array Examples

Example 1: Basic Usage

In this example, the indexOf() method returns -1 because the object { name: 'banana', color: 'yellow' } is a different object instance than the one stored in the array.

let fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'orange', color: 'orange' }
];

// Find the index of an object in the array
let index = fruits.indexOf({ name: 'banana', color: 'yellow' });
console.log(index); // Output: -1 (Not found)

Output
-1

Example 2: Index of Modified Object

In this case, the modified banana object is added to the array, and then indexOf() method returns the index where this modified object is located.

// Example Title: Finding Index of a Modified Object

// Array of objects representing fruits
let fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'orange', color: 'orange' }
];

let banana = { name: 'banana', color: 'yellow' };

// Finding the index of an object after modifying it
fruits.push(banana); // Adding the modified object to the array
let index = fruits.indexOf(banana);
console.log(index); // Output: 3

Output
3


Article Tags :