Search code examples
javascriptarraysfind

indexOf not working correctly in javaScript


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?


Solution

  • 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.