26

I want to return the index of the first element satisfying a unary predicate.

Example:

[1,2,3,4,5,6,7].indexOf((x) => x % 3 === 0) // returns 2

Is there such a function? The alternative I was going to use was

[1,2,3,4,5,6,7].reduce((retval,curelem,idx) => 
{
   if(curelem % 3 === 0 && retval === undefined)
       retval = idx; 
   return retval;
}, undefined);

but of course that would be less efficient since it doesn't stop iterating through the array after it has found the element.

2
  • 2
    Array.prototype.findIndex() Commented Jul 10, 2016 at 21:45
  • @Vohuman post it as an answer (with an example and couple more words) and I'll upvote you Commented Jul 10, 2016 at 21:46

2 Answers 2

35

Yes, there is such function: Array.prototype.findIndex. The method was introduced by ECMAScript 2015 and you need to use a polyfill for supporting older browsers.

Sign up to request clarification or add additional context in comments.

2 Comments

"and it works just like the lambd function" --- this statement looks weird.
Well, I cannot think of what it means actually. I don't know that it means for something "to work like the lambda function". To me (since the standard does not provide an official definition for that), a lambda function === a function expression.
15

yes it exists :

console.log([1,2,3,4,5,6,7].findIndex((x) => x % 3 === 0));

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.