Replace or append array value

JavaScript, Array · Feb 19, 2023

Replaces an item in an array or appends it, if it doesn't exist.

  • Use the spread operator (...) to create a shallow copy of the array.
  • Use Array.prototype.findIndex() to find the index of the first element that satisfies the provided comparison function, compFn.
  • If no such element is found, use Array.prototype.push() to append the new value to the array.
  • Otherwise, use Array.prototype.splice() to replace the value at the found index with the new value.
const replaceOrAppend = (arr, val, compFn) => {
  const res = [...arr];
  const i = arr.findIndex(v => compFn(v, val));
  if (i === -1) res.push(val);
  else res.splice(i, 1, val);
  return res;
};
const people = [ { name: 'John', age: 30 }, { name: 'Jane', age: 28 } ];
const jane = { name: 'Jane', age: 29 };
const jack = { name: 'Jack', age: 28 };
replaceOrAppend(people, jane, (a, b) => a.name === b.name);
// [ { name: 'John', age: 30 }, { name: 'Jane', age: 29 } ]
replaceOrAppend(people, jack, (a, b) => a.name === b.name);
// [
//   { name: 'John', age: 30 },
//   { name: 'Jane', age: 28 },
//   { name: 'Jack', age: 28 }
// ]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Tip: Min and max value in a JavaScript array

    When working with numeric arrays in JavaScript, you might need to find the minimum or maximum value. Here's a quick and easy way to do it.

    JavaScript, Array · Nov 6, 2021

  • Pull values from array based on function

    Mutates the original array to filter out the values specified, based on a given iterator function.

    JavaScript, Array · Oct 22, 2020

  • Stable sort

    Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.

    JavaScript, Array · Oct 22, 2020