0

I need to create a copy of an array so that I can do modification on one array without affecting the other.

for example:

var a = [[1],[2],[3]];
var b = a.slice(0);
b[1].push(100);
b // [[1],[2, 100],[3]];
a // expect: [[1],[2],[3]]; , actual: [[1],[2, 100],[3]];

I have also tried:

var b = new Array(a);

but this puts all [1],[2],[3] to index 0 in the new array.

What am I missing here?

Thanks guys!

2
  • 1
    The slice() method returns a shallow copy [...]. Commented Aug 31, 2018 at 18:33
  • use the JSON trick: b = JSON.parse(JSON.stringify(a)) this will do some kind of a "deep copy", then you can modify b without messing a. Commented Aug 31, 2018 at 18:35

2 Answers 2

2

you also have to copy the inner arrays:

 var b = a.map(sub => sub.slice());
Sign up to request clarification or add additional context in comments.

Comments

0

slice() makes a shallow copy, for n levels you could use JSON.parse(JSON.stringify(a)) or recursion:

var a = [[[1]],[2],[3]];

var b = JSON.parse(JSON.stringify(a))

b[0][0][0] = 999;

console.log(a)

console.log(b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.