Replace an item in an array, by number, without mutation in JavaScript (ES6)

23 August 2018   0 comments   Javascript

Suppose you have an array like this:

const items = ["B", "M", "X"];

And now you want to replace that second item ("J" instead of "M") and suppose that you already know it's position as opposed to finding its position by doing an Array.prototype.find.

Here's how you do it:

const index = 1;
const replacementItem = "J";

const newArray = Object.assign([], items, {[index]: replacementItem});

console.log(items); // ["B", "M", "X"]
console.log(newArray); //  ["B", "J", "X"]

Wasn't immediately obvious to me but writing it down will help me remember.


There's a much faster way and that's to use slice and it actually looks nicer too:

function replaceAt(array, index, value) {
  const ret = array.slice(0);
  ret[index] = value;
  return ret;
const newArray = replaceAt(items, index, "J");

See this codepen.


Your email will never ever be published

Related posts

django-pipeline and Zopfli 15 August 2018
A darn good search filter function in JavaScript 12 September 2018
Related by Keyword:
EditDistanceMatcher - NodeJS script for doing edit distance 1 matching 05 February 2011
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010