0

I have the following code, and as of my knowledge Array.slice() is suppose to make a new copy of the main array, but it is not. As you can see, I am editing array "b" and it is modifying the main array "a", which is not what I want.

let a = [ { "a": true }, { "a": true }, { "a": true } ];
let b = a.slice(1, 2);
b[0].b = false;
console.log(a);

It would really help me if someone could give me a hint on how to make a copy from the main array and then edit it without modifying the main array. Thank you

Edit (Solution):

function copy(obj) {
  return Object.assign({}, obj);
}

let a = [ { "a": true }, { "a": true }, { "a": true } ];
let b = a.slice(1, 2).map(copy);
b[0].b = false;
console.log(a);

credit: Ryan

Shifatul
  • 2,277
  • 4
  • 25
  • 37

0 Answers0