javascript indexOf object value in array

How to use indexOf() method to find object values in an array using JavaScript?

One of the most useful methods that JavaScript array objects provide is the indexOf() method, which allows you to find the index of a particular element within an array. This is especially useful when you're working with arrays that contain objects and you need to find the index of an object based on one or more of its property values.

Syntax:


array.indexOf(searchElement[, fromIndex])
  • searchElement: The element to search for within the array.
  • fromIndex (optional): The index at which to begin the search. If not specified, the search starts at index 0.

The indexOf() method returns the first index at which the searchElement is found within the array. If the element is not found, it returns -1.

Let's take an example of an array of objects:


var cars = [
  {make: "Honda", model: "Civic", year: 2006},
  {make: "Toyota", model: "Camry", year: 2010},
  {make: "Honda", model: "Accord", year: 2015},
  {make: "Ford", model: "Mustang", year: 2018}
];

Now, let's say we want to find the index of the object that has the make "Toyota" and model "Camry". We can use the indexOf() method in the following way:


var index = -1;
for (var i = 0; i < cars.length; i++) {
  if (cars[i].make === "Toyota" && cars[i].model === "Camry") {
    index = i;
    break;
  }
}

This code loops through the cars array and checks each object to see if its make property is "Toyota" and its model property is "Camry". If it finds an object with those properties, it sets the index variable to the index of that object and breaks out of the loop.

Alternatively, we can use the findIndex() method, which is a more concise method to achieve the same result:


var index = cars.findIndex(function(car) {
  return car.make === "Toyota" && car.model === "Camry";
});

The findIndex() method takes a callback function as its argument, which is executed for each element in the array until it finds an element that satisfies the condition specified in the function. The function returns true or false depending on whether the condition is met, and findIndex() returns the index of the first element for which the function returned true.

Both of these methods work similarly, but the findIndex() method is more concise and easier to read.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe