replace
The replace utility replaces the first element in an array that satisfies a predicate with a new value. The original array is not mutated.
Source Code
View Source Code
ts
import type { Predicate } from '../types';
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
/**
* Replaces the first element in an array that satisfies the provided predicate
* function with a new value.
*
* @example
* ```ts
* replace([1, 2, 3], (n) => n === 2, 4) // [1, 4, 3]
* ```
*
* @param array - The array to search.
* @param predicate - A function to test each element of the array.
* @param value - The new value to replace the found element.
*
* @return A new array with the replaced value.
*
* @throws {TypeError} If the first argument is not an array.
*/
export function replace<T>(array: T[], predicate: Predicate<T>, value: T): T[] {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
const index = array.findIndex(predicate);
if (index === -1) return array;
return [...array.slice(0, index), value, ...array.slice(index + 1)];
}Features
- Immutable: Returns a new array; never mutates the original.
- First match only: Only the first matching element is replaced.
- No-op safe: Returns the original array reference if no match is found.
API
ts
function replace<T>(array: T[], predicate: (item: T) => boolean, value: T): T[];Parameters
array: The source array.predicate: A function to test each element; replacement happens on the firsttrue.value: The new value to substitute in place of the matched element.
Returns
- A new array with the first matching element replaced, or the original array if no match.
Throws
TypeError: If the first argument is not an array.
Examples
Replace by Value
ts
import { replace } from '@vielzeug/toolkit';
replace([1, 2, 3, 2], (n) => n === 2, 99);
// [1, 99, 3, 2] — only the first 2 is replacedReplace an Object in a List
ts
import { replace } from '@vielzeug/toolkit';
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
];
const updated = replace(users, (u) => u.id === 2, { id: 2, name: 'Robert' });
// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Robert' }, { id: 3, name: 'Charlie' }]No Match Returns Original
ts
import { replace } from '@vielzeug/toolkit';
const arr = [1, 2, 3];
replace(arr, (n) => n === 99, 0) === arr; // true (same reference)