Search code examples
javascriptarraysecmascript-next

How to update an element of an array based on the index when using spread syntax?


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 ];

Solution

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