Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!