Skip to content

Instantly share code, notes, and snippets.

@kirpalmakanga
Last active June 28, 2025 09:41
Show Gist options
  • Save kirpalmakanga/1c8f7a2bd5935c75547c68b6dc15e234 to your computer and use it in GitHub Desktop.
Save kirpalmakanga/1c8f7a2bd5935c75547c68b6dc15e234 to your computer and use it in GitHub Desktop.
update object(s) in array
export function update<T extends Record<K, unknown>, K extends keyof T>(
arr: T[],
predicate: (item: T, index: number, array: T[]) => boolean,
payload: Partial<T>
) {
const targetIndex = arr.findIndex(predicate);
if (targetIndex > -1) {
return arr.with(targetIndex, { ...arr[targetIndex], ...payload });
}
return arr;
}
export function updateBulk<T extends Record<K, unknown>, K extends keyof T>(
arr: T[],
predicate: (item: T, index: number, array: T[]) => boolean,
payload: Partial<T>
) {
return arr.map((item, index) => {
if (predicate(item, index, arr)) {
return { ...item, ...payload };
}
return item;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment