javascript update array of objects with reduce site:stackoverflow.com 1

javascript update array of objects with reduce site:stackoverflow.com

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);
}

Here is what the above code is Doing:
1. The upsert function takes an array and an element as arguments.
2. If the element is already in the array, it replaces it. Otherwise, it adds it to the array.

Similar Posts