Search code examples
javascriptarrayssorting

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?


Solution

  • ES2023 Array Method toSorted():

    The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

    const arr = [2, 1, 3];
    const arrSorted = arr.toSorted();
    console.log(arr); //[2, 1, 3]
    console.log(arrSorted); //[1, 2, 3]