1

I'm sure this is a stupid thing, but i can't solve it.

If i do this:

var arr = [1, 2, 3, "up"];
var duplicate = arr;
duplicate[3] = "down";
console.log(arr[3]); //"down"
console.log(duplicate[3]); //"down"

So why the original array got modified too? It is related to the fact that they point to the same array?

How to modify only the duplicate?

pietrovismara
  • 6,102
  • 5
  • 33
  • 45
  • Well it looks my duplicate it's not a duplicate, but my question is a duplicate! Sorry, but sometimes it's hard to find even the way to express a question in english if you're not native english, so i didn't find similar questions even if i looked for. – pietrovismara Dec 18 '14 at 18:57

2 Answers2

5

You need to clone your duplicate array... you can use the slice() method to do it:

var arr = [1, 2, 3, "up"];
var duplicate = arr.slice(0);
duplicate[3] = "down";
console.log(arr[3]); //"up"
console.log(duplicate[3]); //"down"
c0deNinja
  • 3,956
  • 1
  • 29
  • 45
1

The original array was modified because using var duplicate = arr just means the value of duplicate is now equal to the value of arr. Changing either one will change the value of the array.

As for copying the array and its contents, this post has a full write up How do I correctly clone a JavaScript object?

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273