findAndReplace
The findAndReplace() function searches for the first element that satisfies a predicate, replaces it with a new value, and returns the updated array. If no element matches, it returns undefined.
Interactive example
Syntax
Classic signature
typescript
function findAndReplace<
GenericArray extends readonly unknown[],
GenericValue extends AnyValue,
>(
input: GenericArray,
predicate: (
element: GenericArray[number],
params: { index: number }
) => boolean,
value: GenericValue,
): (GenericArray[number] | GenericValue)[] | undefinedCurried signature
typescript
function findAndReplace<
GenericArray extends readonly unknown[],
GenericValue extends AnyValue,
>(
predicate: (
element: GenericArray[number],
params: { index: number }
) => boolean,
value: GenericValue,
): (input: GenericArray) => (GenericArray[number] | GenericValue)[] | undefinedParameters
input: Source array.predicate: Function called for each element with the element and its index. Must returntruewhen the element is targeted.value: New value that replaces the found element.
Return value
A new array with the element replaced, or undefined if no element satisfies the predicate.
See also
find- Finds the first element that satisfies a conditionfindAndSpliceReplace- Replaces a segment viasplice
