findLast
The findLast utility returns the last element in an array that passes the provided test function. Conceptually, it works like find() but searches backwards from the end of the array.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
import type { Predicate } from '../types';
/**
* Finds the last element in the array that satisfies the provided predicate function.
* If no such element is found, returns the specified default value (if provided).
*
* @example
* ```ts
* const arr = [1, 2, 3, 4, 5];
* const isEven = (num) => num % 2 === 0;
* findLast(arr, isEven); // 4
* findLast(arr, (num) => num > 5, 0); // 0
* findLast(arr, (num) => num > 5); // undefined
* ```
*
* @param array - The array to search through.
* @param predicate - A function to test each element of the array.
* @param [defaultValue] - The value to return if no element satisfies the predicate.
*
* @return The last element in the array that satisfies the predicate, or the default value if none match.
*/
export function findLast<T>(array: T[], predicate: Predicate<T>, defaultValue?: T) {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
for (let index = array.length - 1; index >= 0; index--) {
if (predicate(array[index], index, array)) {
return array[index];
}
}
return defaultValue;
}
findLast.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Right-to-Left Search: Starts searching from the end of the array for better efficiency when looking for the most recent match.
- Default Value Support: Specify a fallback value instead of always receiving
undefined. - Type-safe: Properly infers the return type based on the array and default value.
API
ts
function findLast<T>(
array: T[],
predicate: (item: T, index: number, array: T[]) => boolean,
defaultValue?: T,
): T | undefined;Parameters
array: The array to search.predicate: The function to test each element. It receives:item: The current element.index: The index of the current element.array: The original array.
defaultValue: Optional. A value to return if no elements match the predicate.
Returns
- The last matching element, or the
defaultValueif provided, orundefined.
Examples
Finding the Last Match
ts
import { findLast } from '@vielzeug/toolkit';
const numbers = [1, 2, 3, 4, 5, 6];
// Find the last even number
findLast(numbers, (x) => x % 2 === 0); // 6Using a Default Value
ts
import { findLast } from '@vielzeug/toolkit';
const logs = [
{ level: 'info', message: 'Startup' },
{ level: 'warn', message: 'High memory' },
{ level: 'info', message: 'Processing' },
];
// Find the last error with fallback
const lastError = findLast(logs, (l) => l.level === 'error', { level: 'none', message: 'No errors' });
// { level: 'none', message: 'No errors' }Implementation Notes
- Throws
TypeErrorif the first argument is not an array. - Stops searching as soon as the first match (from the right) is found.
- Does not modify the original array.