I am looking to create a function that accepts an array of objects, one object, and a key as input. The goal is for the function to return an array of objects with the new object at position 0 if it is not already in the array, or in the same position if it is. The key provided will be used to compare the objects, and can only be either a string or a number.
I have already written a function for this purpose, but it is important to note that each object must have an "id" property included.
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;
}