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.

4
  • 3
    var array2 = array1.slice(); Commented Aug 9, 2016 at 7:33
  • Why is the default behavior to reference the original array instead of copying it? Commented Aug 9, 2016 at 7:34
  • stackoverflow.com/questions/7486085/…. Some methods are doing changes on reference, some create new array. Check array documentation. Commented Aug 9, 2016 at 7: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. Commented Aug 9, 2016 at 7:39

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

"you're making a shallow copy of the object," - Nope, you're not making a copy of the object at all, you're just making a second reference to the same object.
@nnnnnn that's more accurate
0

You can copy a array with slice method

var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1.slice();

1 Comment

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.

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.