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

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

    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))
    

提交回复
热议问题