skip to Main Content

‘a’ array wasn’t affected.

const a = [1,2,3]
const b = [...a] // shallow copy

b[0] = 9

console.log(a) // [1,2,3]
console.log(b) // [9,2,3] results as expected


----------

const a = [{name:"John"},{name:"George"}];
const b = [...a];

b[0] = {name:"Oliver"}

console.log(a) // [ { name: 'John' }, { name: 'George' } ]
console.log(b); // [ { name: 'Oliver' }, { name: 'George' } ] results as expected


----------

const a = [{name:"John"},{name:"George"}];
const b = [...a];

b[0].age = 21

console.log(a); //[ { name: 'John', age: 21 }, { name: 'George' } ]
console.log(b); // [ { name: 'John', age: 21 }, { name: 'George' } ]

// why were affected ‘a’ array ?

Why were they both affected? It shows the same reference, but in the other 2 examples above, there was no change, only the ‘b’ array changed.

2

Answers


  1. It happens because the reference of the object is not changing, internally when you make a shallow copy of the "a" array, you are making a copy of a reference to those objects, so after changing b[0] object you are also affecting a[0] since its the same object

    Login or Signup to reply.
  2. In the second example, you assigned b[0] to totally new object ( with new referance ), but in the third example, you changed the age in the object with reference shared between both a and b arrays.

    If you need the same behavior you need to map new references.

    const a = [{name:"John"},{name:"George"}];
    const b = [...a.map(o => ({...o}))];
    
    b[0].age = 21
    
    console.log(a); //[ { name: 'John' }, { name: 'George' } ]
    console.log(b); // [ { name: 'John', age: 21 }, { name: 'George' } ]

    Here [...a.map(o => ({...o}))] will replace all the objects inside a array with a new copy but with a different reference.

    Update
    Or as shared by @Andy and @Amadan, you can use structuredClone to deep clone the array.

    const a = [{name:"John"},{name:"George"}];
    const b = structuredClone(a);
    
    b[0].age = 21
    
    console.log(a); //[ { name: 'John' }, { name: 'George' } ]
    console.log(b); // [ { name: 'John', age: 21 }, { name: 'George' }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search