3

Consider an array as

const foo = [1, 2, 3];

Now if I want to replace the second element I can just do:

foo[1] = 4; or

foo.splice(1,1,4); or

const foo = [1, 2, 3];

console.log([...foo.slice(0, 1), 4, ...foo.slice(2)]);
// I know this creates a new array unlike the above two ways.

but when we use spread operator for shallow copying objects we can dynamically overwrite a property like:

const someObject = {
 a: 1,
 b: 2,
 c: 3
}
const propertyToChange = 'b';

const newObject = { ...someObject, [propertyToChange]: 4 };

So, is there an equivalent of this for arrays? Maybe something like the following to change an element based on the index.

const newArray = [...oldArray, [dynamicIndex]: 4 ];
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32

1 Answers1

7

Sort of: you can use Object.assign:

const newArray = Object.assign([...oldArray], {[dynamicIndex]: 4});
// Or
const newArray = Object.assign([], oldArray, {[dynamicIndex]: 4});

That works because arrays are objects.

Live Example:

const oldArray = [1, 2, 3, 4, 5, 6];
const dynamicIndex = 3; // The fourth entry
const newArray = Object.assign([], oldArray, {[dynamicIndex]: "four"});
console.log(newArray);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Nice. I'm assuming some like `const newArray = [...oldArray, [dynamicIndex]: 4 ];` isn't implemented because of it kind of clashes with the object's syntax. Could that be the reason? – Ramesh Reddy Apr 02 '20 at 18:02
  • 2
    @RameshReddy - I don't know the specific reason. That does look like it would be awkward for the parser. Up until the `:` it looks like an array literal containing `dynamicIndex`. I *think* they try to avoid too much lookahead when they can... – T.J. Crowder Apr 02 '20 at 18:09
  • (I'm disappointed to see that I didn't include the trick above in Chapter 5 of my book out in June/July [see my profile if you're interested]... :-| Ah, well, there's always the website and perhaps a 2nd edition...) – T.J. Crowder Apr 02 '20 at 18:11
  • @T.J.Crowder, prior art: https://stackoverflow.com/questions/51188539/javascript-how-to-merge-arrays-so-that-the-indexes-of-original-elements-in-both – Nina Scholz Apr 02 '20 at 18:20
  • @NinaScholz - I did wonder if this had been covered somewhere, didn't look hard enough clearly. I've marked the dupe. Can't delete since it's accepted, but... – T.J. Crowder Apr 02 '20 at 18:40