I want to create a function that takes in input an array of Objects, an Object, and a key and returns an Array of Objects that contains the new Object on position 0 if it's a new Object or at the same position if it's not a new one. The key is used to compare the Objects and can be only a string or a number.
I wrote this one but it's mandatory to have an id property inside the Objects.
export function addOrReplaceById<T extends Array<{ id: string }>>(
arrayOfObjects: T,
newObject: { id: string }
): T {
const index = arrayOfObjects.findIndex((object) => object.id === newObject.id);
if (index === -1) {
arrayOfObjects.unshift(newObject);
} else {
arrayOfObjects[index] = newObject;
}
return arrayOfObjects;
}