Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the indexOf an element using a criteria function

Tags:

javascript

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)
like image 741
Nick Grealy Avatar asked Nov 24 '25 04:11

Nick Grealy


1 Answers

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

like image 72
Code Maniac Avatar answered Nov 26 '25 19:11

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!