2

How can I use findIndex when I have a array of strings or objects. Both of the above code returns -1

console.log(['kk', 'll', 'mm', 'pp'].findIndex(function(x) { x == 'mm'}))
console.log([{name: 'kk'},{name: 'vv'},{name: 'mm'},{name: 'ok'}].findIndex(function(x) { x.name == 'mm'}))

jsfiddle

1 Answer 1

6

You have to return the result of the condition so Array.findIndex knows if the value was found or not

['kk', 'll', 'mm', 'pp'].findIndex(function(x) { return x == 'mm'})

It should be noted that used like this, with an array of just strings, indexOf works just fine

['kk', 'll', 'mm', 'pp'].indexOf('mm')

but for an array of objects, as in the second example, it's very useful to have a callback

[
    {name: 'kk'},
    {name: 'vv'},
    {name: 'mm'},
    {name: 'ok'}
].findIndex(function(x) { 
    return x.name == 'mm';
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.