Open In App

JavaScript indexOf() method in an Object Array

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • element: the element to be searched in the input array
  • start: the index from which the search has to begin. The default value is set to 0.

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.

JavaScript
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.

JavaScript
// 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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads