Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ];
like image 541
Ramesh Reddy Avatar asked Dec 10 '25 21:12

Ramesh Reddy


1 Answers

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);
like image 134
T.J. Crowder Avatar answered Dec 12 '25 09:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!