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.
indexOf(v) instead, where ~ is the JavaScript bitwise NOT operator.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With