I'd like to get the indexOf an object in an array, by using a criteria function.
attempt1: works, but is inefficient, as I have to iterate the array twice.
attempt2: doesn't work (obviously), but indicates what I'd like to achieve.
const dataSet = [{ name: "obj1" }, { name: "obj2" }, { name: "obj3" }, { name: "obj4" }, { name: "obj5" }]
const attempt1 = dataSet.indexOf(dataSet.find(d => d.name === 'obj3'))
const attempt2 = dataSet.indexOf(d => d.name === 'obj3')
console.log(attempt1)
console.log(attempt2)
You're probably looking for findIndex
const dataSet = [{ name: "obj1" }, { name: "obj2" }, { name: "obj3" }, { name: "obj4" }, { name: "obj5" }]
const attempt2 = dataSet.findIndex(d => d.name === 'obj3')
console.log(attempt2)
Why second one is not working whereas first attempt is working ?
indexOf expects a searchElement value to be searched so in the first attempt you used find inside indexOf which returns a value whereas in second attempt you passed a function which not what indexOf expects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With