Is there JavaScript in indexOf (lambda) or similar?

I want to return the index of the first element satisfying the 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 it will be less efficient as it does not stop the repetition through the array after it has found the element.

+4
source share
2 answers

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

+6
source

yes, it exists:

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

All Articles