3

I'm trying to print out an unsorted version of an array and a sorted version of array using this code:

var sortArrayNumber = function(a, b) {
    return a - b;
};

var array = [5, 2, 1044, 3, 126];
var sortedArray = [];

sortedArray = array;

sortedArray.sort(sortArrayNumber);

document.write(array + " and " + sortedArray);

This is not the actual code that I'm going to use, I'm just testing it. And when I test it using jsfiddle, it outputs

2,3,5,126,1044 and 2,3,5,126,1044

But I want it to output

5,2,1044,3,126 and 2,3,5,126,1044

So, how do I stop it from doing that?

BTW, I'm self teaching myself JavaScript so my knowledge of it isn't great

Kakol20
  • 39
  • 4

1 Answers1

3

You need to apply the sort on a copy of the original array with Array#slice,

The slice() method returns a shallow copy of a portion of an array into a new array object.

because sort works in place.

sortedArray = array.slice();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392