How can I get the index of an obj in an array of objects?
const arr = [ {x: "a", y: 1}, {x: "b", y: 2} ]
const i = arr.indexOf({x: "a", y: 1})
console.log(i) // output: -1
I would expect the output to be 0, but it’s telling me the object does not exist.
ghukahr
November 12, 2018, 11:50pm
2
You can do that if you have the reference for the object. Otherwise you have to use findIndex
.
arr.findIndex(obj => obj.x === "a" && obj.y === 1);
I’m passing the object as a parameter dynamically, and it has more keys than just x and y. I am trying to implement a next button functionality. I think I’ll just use lodash _.findIndex
method to get the index of the object.
handleNextButton = product => {
console.log(product);
};
I need the index of that object in the array.
ghukahr
November 13, 2018, 2:20am
4
It looks like you have the reference of the object, in that case you can actually use the normal indexOf
and it should just work.