Peter Olson Peter Olson - 4 months ago 25
Javascript Question

How can you sort an array without mutating the original array?

Let's suppose I wanted a sort function that returns a sorted copy of the inputted array. I naively tried this

function sort(arr) {
return arr.sort();

and I tested it with this, which shows that my
method is mutating the array.

var a = [2,3,7,5,3,7,1,3,4];
alert(a); //alerts "1,2,3,3,3,4,5,7,7"

I also tried this approach

function sort(arr) {
return Array.prototype.sort(arr);

but it doesn't work at all.

Is there a straightforward way around this, prefereably a way that doesn't require hand-rolling my own sorting algorithm or copying every element of the array into a new one?


Just copy the array. There are many ways to do that:

function sort(arr) {
  return arr.concat().sort();

// Or:
return; // For array-like objects