-2

my code is :

[{a:1},{b:2},{c:3}].indexOf(obj=>{return obj.a ==1})

I expect return 0 but result is -1

what is the problem?

1 Answers1

1

The main difference are the parameters of these functions:

  • Array.prototype.indexOf() expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types (like string, number, or boolean).
  • Array.prototype.findIndex() expects a callback as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.

This question is similar to this and the answer can also be found there.

Quatban Taco
  • 310
  • 1
  • 15
  • 2
    If you found a duplicate you can mark the current question as one, no need to answer it again. This can be done by casting a [close vote](https://stackoverflow.com/help/privileges/close-questions) (requires 3k reputation) or by [flagging](https://stackoverflow.com/help/privileges/flag-posts) it as one (requires 15 reputation) – Reyno Oct 19 '22 at 11:05
  • @Reyno how could he? – JavaScript Oct 19 '22 at 11:06