find
The find utility returns the first element in an array that passes the provided test function. It also supports an optional default value to be returned if no match is found, providing a more ergonomic alternative to the native Array.prototype.find().
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 first element in an array that satisfies a predicate function.
*
* @example
* ```ts
* const arr = [1, 2, 3, 4, 5];
* const isEven = (num) => num % 2 === 0;
* find(arr, isEven); // 2
* find(arr, (num) => num > 5, 0); // 0
* find(arr, (num) => num > 5); // undefined
* ```
*
* @param array - The array to search through.
* @param predicate - A function that is called for each element in the array.
* @param [defaultValue] - (optional) value to return if no element satisfies the predicate.
*
* @return The first element in the array that satisfies the predicate, or the default value if none match.
*/
export function find<T>(array: T[], predicate: Predicate<T>, defaultValue?: T) {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
for (let index = 0; index < array.length; index++) {
if (predicate(array[index], index, array)) {
return array[index];
}
}
return defaultValue;
}
find.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Short-circuiting: Stops searching as soon as the first match is found.
- 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 find<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 first matching element, or the
defaultValueif provided, orundefined.
Examples
Basic Searching
ts
import { find } from '@vielzeug/toolkit';
const numbers = [1, 3, 4, 7, 8];
// Find the first even number
find(numbers, (x) => x % 2 === 0); // 4Using a Default Value
ts
import { find } from '@vielzeug/toolkit';
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
// Find user by ID with fallback
const user = find(users, (u) => u.id === 99, { id: 0, name: 'Guest' });
// { id: 0, name: 'Guest' }Implementation Notes
- Throws
TypeErrorif the first argument is not an array. - Stops iterating as soon as the predicate returns truthy.
- Does not modify the original array.