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: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
The last 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(polyArrFindLast(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(polyArrFindLast([4, 6, 8, 12], isPrime)); // undefined, not found
console.log(polyArrFindLast([4, 5, 7, 12], isPrime)); // 7
The polyArrFindLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
The polyArrFindLast() method is an iterative method. It calls a provided callbackFn function once for each element in an array in descending-index order, until callbackFn returns a truthy value. polyArrFindLast() then returns that element and stops iterating through the array. If
callbackFn
never returns a truthy value, polyArrFindLast() 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.polyArrFindLast() 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 ofcallbackFn
. Therefore:callbackFn
will not visit any elements added beyond the array's initial length when the call to polyArrFindLast() began.callbackFn
, its value passed to thecallbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined.