Last active
June 28, 2025 09:41
-
-
Save kirpalmakanga/1c8f7a2bd5935c75547c68b6dc15e234 to your computer and use it in GitHub Desktop.
update object(s) in array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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