The array or array like object of elements to be searched.
A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
Optional
thisArg: anyThe first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(polyArrFind(inventory, isCherries));
// { name: 'cherries', quantity: 5 }
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log(polyArrFind([4, 6, 8, 12], isPrime)); // undefined, not found
console.log(polyArrFind([4, 5, 8, 12], isPrime)); // 5
The polyArrFind() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
The polyArrFind() method is an iterative method. It calls a provided
callbackFn
function once for each element in an array in ascending-index order, untilcallbackFn
returns a truthy value. polyArrFind() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, polyArrFind() returns undefined.callbackFn
is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.polyArrFind() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of
callbackFn
. Therefore:callbackFn
will not visit any elements added beyond the array's initial length when the call to polyArrFind() began.callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined.