How do I save a copy of an array before sorting? [duplicate]

This question already has an answer here:

I’m trying to save a copy of the array before I sort it:

words_Array = ["Why", "doesnt", "this", "work?"];

var sortedWords_Array = words_Array;

sortedWords_Array.sort(function(a, b){
    return b.length - a.length;
});

alert("sortedWords_Array is :"+sortedWords_Array);
alert("words_Array is :"+words_Array);

After I sort sortedWords_Array, they’re both sorted for some reason. http://jsfiddle.net/zv39J/ Why is that?

Comments 4

  • Because in javascript, arrays are passed by reference which means that when you make one array equal to another it will change both whenever you make an edit to one. To fix this in your example change the following line:

    var sortedWords_Array = words_Array;
    

    to:

     //make a copy of array by using slice
     var sortedWords_Array = words_Array.slice(0);
    

    See here for other uses and a more in-depth explanation:

    slice does not alter the original array, but returns a new “one level
    deep” copy that contains copies of the elements sliced from the
    original array.

    Array.prototype.slice()

  • This wont work because when you try to assign
    var sortedWords_Array = words_Array;

    The reference of words_array is passed to sortedWords_Array. So any change made to sortedWords_Array will be reflected on words_array.

    Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:

    var a =[[1], [2], [3]];
    var b = a.slice();
    
    b.shift().shift();
    // a is now [[], [2], [3]]
    

    Note that although I’ve used shift().shift() above, the point is just that b[0][0] contains a pointer to a[0][0] rather than a value.

    Likewise delete(b[0][0]) also causes a[0][0] to be deleted and b[0][0]=99 also changes the value of a[0][0] to 99.

    jQuery's extend method does perform a deep copy when a true value is passed as the initial argument:

    var a =[[1], [2], [3]];
    var b = $.extend(true, [], a);
    
    b.shift().shift();
    // a is still [[1], [2], [3]]
    
  • Use the slice function to make a fast copy.

    http://jsfiddle.net/zv39J/2/

    On another note—alerts are terrible. No one wants to click a jsfiddle only to be greeted by a series of alert windows. I’ve updated the fiddle to include jQuery, which allows us to use a nice succinct syntax to make updates to the HTML.

  • Do a slice() on the array to duplicate, and then sort.

    var sortedWords_Array = words_Array.slice();
    

发表评论

电子邮件地址不会被公开。 必填项已用*标注