The Guru
The Guru

Reputation: 115

Updating a sliced array also updates the larger array

I need an explanation for something weird that I noticed with array slicing (NodeJs)

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const b = a.slice(0, 2);

for (let input of b) {
  input.y = 1;
}

console.log(b);
console.log(a);

The output has the array a as well as array b updated, even though in the for loop, I am only updating the elements in array b. What am I missing here?

Edit: I tried looking this up as well as went through the MDN Docs for 'slice' but could unfortunately not find anything.

Upvotes: 0

Views: 65

Answers (3)

DecPK
DecPK

Reputation: 25408

when you use slice you will get a new array but the objects are same that are in a. If you want to add properties without affecting object on a then you should clone the objects.

Remember: Below code snippet will work if there is no nested objects

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const temp = a.slice(0, 2);
const b = [];

for (let obj of temp) {
  const o = { ...obj };
  o.y = 1;
  b.push(o);
}

console.log(a);
console.log(b);

Upvotes: 1

hgb123
hgb123

Reputation: 14891

According to the doc

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end

So basically it creates a new array but the selected elements will still be the same, here are the same references of the objects

You could check it like this by comparing

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const b = a.slice(0, 2);

console.log(a[0] === b[0])
console.log(a[1] === b[1])

Upvotes: 2

Taxel
Taxel

Reputation: 4207

Array.slice creates a copy of the array, so a !== b, but since a is made out of objects, b still retains the references to those identical objects. So any change you make to the objects in one array, also affects the other array.

You have to deep copy a if you want b to contain entirely new objects.

Upvotes: 1

Related Questions