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

后端 未结 6 1136
遇见更好的自我
遇见更好的自我 2020-11-28 04:21

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();
}
         


        
6条回答
  •  独厮守ぢ
    2020-11-28 05:07

    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

提交回复
热议问题