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

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

    You can use slice with no arguments to copy an array:

    var foo,
        bar;
    foo = [3,1,2];
    bar = foo.slice().sort();
    
    0 讨论(0)
  • 2020-11-28 05:01

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-11-28 05:17

    Try the following

    function sortCopy(arr) { 
      return arr.slice(0).sort();
    }
    

    The slice(0) expression creates a copy of the array starting at element 0.

    0 讨论(0)
提交回复
热议问题