;

How to Get the Index of an Array that Contains Objects in JavaScript


Tutorialsrack 27/11/2021 Jquery Javascript

In this article, you’ll learn how to get the index of an array that contains objects in javascript.  In JavaScript, there are various methods in JavaScript that can help you to access the index of the object from the array of an object. 

Here are some examples to get the index of an array that contains objects in javascript.  

Example 1: Map() Method

In this example, we used the map() method and the map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It calls a function once for each element in an array.

Example 1 - Map() Method
let array = [{
  prop1: 'Tom',
}, {
  prop2: 'Chris',
}, {
  prop3: 'Rocky',
}, {
  prop4: 'John',
}];
function arrayMap() {
  let pos = array.map(function (e) {
    return e.prop3;
  }).indexOf('Rocky');
  console.log("Index of 'Rocky'  is = " + pos);
}
arrayMap();

//Output ==> "Index of 'Rocky'  is = 2"

Example 2: for loop

In this example, we used the for loop and it is another fast method is the for loop set up inside a prototype:

Example - for Loop
let array = [{
  prop1: 'Tom',
}, {
  prop2: 'Chris',
}, {
  prop3: 'Rocky',
}, {
  prop4: 'John',
}];

Array.prototype.indexOfObject = function (property, value) {
  for (let i = 0, len = this.length; i < len; i++) {
    if (this[i][property] === value) return i;
  }
  return -1;
}
console.log("Index of 'Chris' is = "+array.indexOfObject("prop2", "Chris"));

//Output ==> "Index of 'Chris' is = 1"

Example 3: findIndex() method

In this example, You can also use a native and convenient findIndex() method. The findIndex() method returns the index (position) of the first element that passes a test. Otherwise, it returns -1, indicating that no element passed the test.

Example 3 - findIndex() method
let array = [{
  prop1: 'Tom',
}, {
  prop2: 'Chris',
}, {
  prop3: 'Rocky',
}, {
  prop4: 'John',
}];

let index = array.findIndex( element => {
  if (element.prop2 === 'Chris') {
    return true;
  }
});

console.log("Index of 'Chris' is = "+index);
//Output ==> "Index of 'Chris'  is = 1"

I hope this article will help you to understand how to get the index of an array that contains objects in javascript. 

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags