Searching for items in an array has been the point of discussion for many years and debate on what is the best and optimum way for searching for objects has had many solutions, some effective and some not.
However, with the all new findIndex
method on Array.prototype
you have the flexibility to search for objects using your own comparison callback method.
The findIndex
method returns the index of the first element in an array if the callback method passed to it returns true
, otherwise it returns -1
.
const isPerfectSquare = (num) => {
return num > 0 && Math.sqrt(num) % 1 === 0;
}
console.log([1, 3, 8, 9, 12].findIndex(isPerfectSquare)); // 1
console.log([1, 6, 7, 10, 14].findIndex(isPerfectSquare)); // -1
There are two facts you should know:
array.findIndex(function(currentValue, index, arr), thisValue);
this
value inside the function, otherwise undefined
will be passed.It will return the index of the found item or -1
if the callback function is not satisfied.
When the findIndex
is called with one or two arguments, the following steps are executed:
O
be ? ToObject(this value)
len
be ? LengthOfArrayLike(O)
IsCallback(predicate)
is false
, throw a TypeError exceptionk
be 0k < len
Pk
be ! ToString(k)
kValue
be ? Get(O, Pk)
testResult
be ! ToBoolean(? Call(predicate, thisArg, « kValue, k, O »))
testResult
is true
, return k
k
to k + 1
-1