Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have an indexOf(lambda) or similar?

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.

like image 270
user6048670 Avatar asked Jul 10 '16 21:07

user6048670


People also ask

What can I use instead of indexOf in JavaScript?

indexOf(v) instead, where ~ is the JavaScript bitwise NOT operator.

What is indexOf in JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

What is the difference between indexOf and findIndex in JavaScript?

findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise. indexOf - Returns the index of the first occurrence of a value in an array.

Which is better includes or indexOf?

I would suggest using the includes() method to check if the element is present in the array. If you need to know where the element is in the array, you need to use the indexOf() method.


1 Answers

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.

like image 144
undefined Avatar answered Nov 01 '22 02:11

undefined