Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, preferably a way that doesn't require hand-rolling my own sorting algorithm or copying every element of the array into a new one?

like image 207
Peter Olson Avatar asked Mar 06 '12 22:03

Peter Olson


People also ask

Does sort mutate original array?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


2 Answers

You need to copy the array before you sort it. One way with es6:

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

like image 92
Putzi San Avatar answered Oct 03 '22 09:10

Putzi San


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 
like image 42
Rob W Avatar answered Oct 03 '22 08:10

Rob W