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

后端 未结 6 1137
遇见更好的自我
遇见更好的自我 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:03

    Anyone who wants to do a deep copy (e.g. if your array contains objects) can use:

    let arrCopy = JSON.parse(JSON.stringify(arr))
    

    Then you can sort arrCopy without changing arr.

    arrCopy.sort((obj1, obj2) => obj1.id > obj2.id)
    

    Please note: this can be slow for very large arrays.

提交回复
热议问题