In your first approach, no need for Lodash thanks to findIndex()
:
function upsert(array, element) { // (1)
const i = array.findIndex(_element => _element.id === element.id);
if (i > -1) array[i] = element; // (2)
else array.push(element);
}
Example:
const array = [
{id: 0, name: 'Apple', description: 'fruit'},
{id: 1, name: 'Banana', description: 'fruit'},
{id: 2, name: 'Tomato', description: 'vegetable'}
];
upsert(array, {id: 2, name: 'Tomato', description: 'fruit'})
console.log(array);
/* =>
[
{id: 0, name: 'Apple', description: 'fruit'},
{id: 1, name: 'Banana', description: 'fruit'},
{id: 2, name: 'Tomato', description: 'fruit'}
]
*/
upsert(array, {id: 3, name: 'Cucumber', description: 'vegetable'})
console.log(array);
/* =>
[
{id: 0, name: 'Apple', description: 'fruit'},
{id: 1, name: 'Banana', description: 'fruit'},
{id: 2, name: 'Tomato', description: 'fruit'},
{id: 3, name: 'Cucumber', description: 'vegetable'}
]
*/
(1) other possible names: addOrReplace()
, addOrUpdate()
, appendOrUpdate()
, insertOrUpdate()
…
(2) can also be done with array.splice(i, 1, element)
Note that this approach is “mutable” (vs “immutable”): it means instead of returning a new array (without touching the original array), it modifies directly the original array.