chevron_left

Find index of object in array in Javascript

Object in Javascript is a non-primitive data type that acts as a container for storing other data types in a key-value pair. Unlike primitive data types, the index of an object with a specific property in an array of objects cannot be obtained by explicitly calling the `indexOf()` method of the array. In this article we are going to look at ways of finding the index of an object in an array in Javascript.



Introduction

Arrays in Javascript can be used to store values of mixed types. Although in a practical term, it is more likely to see an array as a collection of items of the same datatype. Arrays store data in a contiguous memory location and each data can be assessed by an index.
As objects, Javascript arrays have many useful methods that help in manipulating the items in the array. One of such is the indexOf() method that returns the index of an item within the array. If the items within the array are primitive data types, we can simply pass the value of the item to the indexOf() method to get the index of the array.

const arr = ["apple", "orange", "grape"];
arr.indexOf("orange");  // 1

That works quite fine, but what happens if it's an array of objects.

const arr = [{id:6},{id:9},{id:3}];
arr.indexOf({id:3});  // -1

The method returns -1 which means that the item was not found, since in Javascript {id:3} === {id:3} will return false because both are treated as distinct objects even if they have same property.
So, if I had such array and I wanted to get the index of the object with an id of 3, how would I do that? Well, follow along!

Method 1: A naive approach

In a logical sense, to find the index of an object with a specific property, we could basically loop through each object starting from the first object with an index of 0 and keep comparing the property of the objects with our target property. When an object's property matches that of our target it will simply return the index.
With that being said, any looping statement can be used to accomplish this. In this example we are going to use the for…in loop statement.



let arr = [{id:6},{id:9},{id:3}];
let target = 3;

for(index in arr){
    if(arr[index].id === target){
        console.log(index);
        break;
    }
}

// output : 2

The for…in statement loops over the properties of an object, in our case the indices of the array.

Method 2: Using the `findIndex()` method

ES6 (Javascript 2015) introduces the findIndex() method of an array. The method takes a function, calls the function on each item in the array, and returns the index of the item that passes the condition declared in the function. If no match is found it returns -1

Syntax:
array.findIndex(function(currentValue, index, arr), thisValue)

  • function : A function to call each array element on. This is required.
  • currentValue : Indicates the current element of the array the function is been called on.
  • index : Stores the index of the currentValue
  • arr : Points to the array of the currentValue
  • thisValue : an optional argument to specify the this value to be used by the function. undefined by default.

To find the index of an object by a specific property using the findIndex() method, we simply:

  • Call the `findIndex()` method on the array with the object we are interested in.
  • Within the passed function, check if the object's property matches that of our target and return `true`
  • The `findIndex()` method returns the index of the object that the function returns `true` on.

let arr = [{id:6},{id:9},{id:3}];
let target = 3;

const index = arr.findIndex(obj =>.obj.id === target);
console.log(index);  // 2

The findIndex() method calls the callback function (the arrow function in our case) on each item in the array. The callback function returns true of false depending on the value of the property of the current object. If the iteration ends and the callback function doesn't return a truthful value, the findIndex() method returns -1

Internet Explorer 11 (or earlier) does not have support for the `findIndex()` method. If you wish to support this kind of browser, you can go for the first approach discussed above or check out the next example below.

Method 3: Working with the `map()` method

As discussed earlier, Javascript array has an indexOf() method that returns the index of the first occurrence of a value passed to it.

const arr = ["apple", "orange", "grape"];
arr.indexOf("orange");  // 1

Ideally, if we can get the values of the target property we are looking for in the same order as the array, then we can simply call the indexOf() to get the index.
That's where the map() method comes in. The map() method creates a new array populated by the return values of the function passed to it which is called on each item in the array the method is called on.
To get the index of an object with a specific property using the map() method, we simply:

  • Call the `map()` method on the array and return only the value of the target property in the callback function.
  • Call the `indexOf()` method on the new array returned by the `map()` method.
  • The index of the object is returned by the `indexOf()` method.

let arr = [{id:6},{id:9},{id:3}];
let target = 3;
let new_arr = arr.map(obj => obj.id);
const index = new_arr.indexOf(target);
console.log(index);  // 2
console.log(new_arr);  // [6, 9, 3]

Just like the findIndex() method, if the indexOf() method does not find a match in the array it returns -1

The `map()` method does not affect the original array in any way, it only iterates over the values and returns a new array with items in the same order as the original array.

Conclusion

In this article, we have seen three ways of getting the index of an object with a specific property in an array. The findIndex() method proves to be more concise and elegant in implementation and should be the prefer method if you target only modern browsers. However, if you still wish to support old browsers, then using the map() method is preferable.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

JavaScript remove element from array by index. Bushra Rubab - Sep 17
TypeError: 'str' object does not support item assignment zhteja - Aug 1
Python read file line by line into array Ferdy - Jul 19
Valueerror: could not broadcast input array from shape Hussain Zafar - Jun 18
Object doesn't support this property or method. Bushra Rubab - Sep 25
The truth value of an array with more than one element is ambiguous. use a.any() or a.all() AAbouelenien - Sep 22
Given an array of ints, return true if the array contains a 2 next to a 2 somewhere. NoirHusky - Sep 8
Pandas data cast to NumPy dtype of object. check input data with np.asarray(data) Ankur Ranpariya 1 - Aug 19
TypeError: object of type 'NoneType' has no len() zhteja - Aug 14
Object of type 'zip' has no len() Aizhamal Zhetigenova - Jun 1
How to print an arraylist in java sadmin - May 10
TypeError: 'int' object is not iterable in Python Ferdy - Sep 30
Sum of odd numbers from 1 to 50 in Python Ferdy - Aug 10
Sum of even numbers from 1 to 100 in Python Ferdy - Aug 8
Program to calculate number of vowels in a string in Python Ferdy - Aug 6
Order a list of numbers without built-in sort, min, max functions in Python Ferdy - Aug 4
Explain the various types of conditional control statement in Python Ferdy - Jul 31
Print the contents of file in reverse order in Python Ferdy - Jul 28
Write Recursive Implementation of Binary Search in Python Ankur Ranpariya - Jul 22
Calculate age from date of birth in javascript. Bushra Rubab - Sep 14