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

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 sort method is mutating the array.
var a = [2,3,7,5,3,7,1,3,4];
sort(a);
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?

Solutions/Answers:

Solution 1:

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

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

// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects

Solution 2:

Another way with es6 (non-deep copy):

const sorted = [...arr].sort();

the spread-syntax as array literal (copied from mdn):

var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Solution 3:

Try the following

function sortCopy(arr) { 
  return arr.slice(0).sort();
}

The slice(0) expression creates a copy of the array starting at element 0.

Related:  Testing javascript with Mocha - how can I use console.log to debug a test?

Solution 4:

You can use slice with no arguments to copy an array:

var foo,
    bar;
foo = [3,1,2];
bar = foo.slice().sort();

Solution 5:

You can also do this

d = [20, 30, 10]
e = Array.from(d)
e.sort()

This way d will not get mutated.

function sorted(arr) {
  temp = Array.from(arr)
  return temp.sort()
}

//Use it like this
x = [20, 10, 100]
console.log(sorted(x))

Solution 6:

I use Object.assign() for most of my copies:

var copyArray = Object.assign([], originalArray).sort();

However, after looking through the OP comments, I researched a bit of deep copying and turns out Object.assign not only performs a shallow copy, but also only selects enumerable and own properties (as answered in this post).