Skip to content

replaceOrAppend

Returns a new array with the first item matching predicate replaced by item — or item appended at the end if no match is found. The common “upsert into a list” pattern.

Available since v3.0.0

import { replaceOrAppend } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { replaceOrAppend } from 'helpers4/array';
replaceOrAppend<T>(array: readonly T[] | null | undefined, item: T, predicate: function): T[]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe source array. `null`/`undefined` are treated as empty.
itemTThe replacement (or new) item
predicatefunctionCalled with each existing item to find what to replace

T[] — A new array with item upserted

Replaces the first match, or appends when nothing matches.

const users = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }];
replaceOrAppend(users, { id: 1, name: 'A' }, (u) => u.id === 1)
// => [{ id: 1, name: 'A' }, { id: 2, name: 'b' }]

A missing id is added at the end rather than silently dropped.

replaceOrAppend([{ id: 1 }], { id: 2 }, (u) => u.id === 2)
// => [{ id: 1 }, { id: 2 }]

View source on GitHub