4

This seems like a simple question but I can't find much info on this.

var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1;
array2.sort(function(a, b) {
    return a - b;
})

Expected behavior: array2 is sorted and array1 is in the original order starting with 4.

Actual result: both arrays are sorted.

How can I sort array1 - while maintaining array1 and storing the results of the sort in array2? I thought that doing array2 = array1 would copy the variable, not reference it. However, in Firefox's console both arrays appear sorted.

tomysshadow
  • 870
  • 1
  • 8
  • 23
  • 3
    `var array2 = array1.slice();` – Tushar Aug 09 '16 at 07:33
  • Why is the default behavior to reference the original array instead of copying it? – tomysshadow Aug 09 '16 at 07:34
  • http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript. Some methods are doing changes on reference, some create new array. Check array documentation. – Maciej Sikora Aug 09 '16 at 07:35
  • Should have realized that the two arrays are one and the same not just with the sort function. I guess that basically makes this a duplicate question, it just wasn't obvious at first the two arrays are always the same not just with the sort function. – tomysshadow Aug 09 '16 at 07:39

2 Answers2

1

That's becasue with var array2 = array1; you're making a new reference to the object, so any manipulation to array2 will affect array1, since the're basically the same object.

JS doesn't provide a propner clone function/method, so try this widely adopted workarround:

var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = JSON.parse(JSON.stringify(array1));
array2.sort(function(a, b) {
    return a - b;
});

Hope it helps :)

alejandromav
  • 933
  • 1
  • 11
  • 24
0

You can copy a array with slice method

var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1.slice();
Community
  • 1
  • 1
Radian Jheng
  • 667
  • 9
  • 20
  • 2
    Note that this makes a shallow copy, which should be fine for the OP's array of numbers but may or may not be enough with an array of objects. – nnnnnn Aug 09 '16 at 07:54