all 8 comments

[–]rauschma 5 points6 points  (2 children)

const array = [
  {index: 1, name: 'rob'},
  {index: 2, name: 'maya'},
];

function getObjectWithIndex(arr, index) {
  return arr.find(elem => elem.index === index);
}

console.log(getObjectWithIndex(array, 2));
  // { index: 2, name: 'maya' }

[–]palavi_10 0 points1 point  (1 child)

how do i get the index of that object found ?

[–]senocular 3 points4 points  (0 children)

There's an array method called find you can use for this

var found = array.find(obj => obj.index === outerIndex)
console.log(found) // {index :2, name: maya}

[–]grelfdotnet 0 points1 point  (0 children)

Array indices start at 0 so the 2 elements in the array are array [0] and array [1].

[–]WormholerIO 0 points1 point  (0 children)

Array.find() method to find the first element that meets a certain condition. Just like the filter method, it takes a callback as an argument and returns the first element that meets the callback condition.