Does .sort function change original array?

前端 未结 3 1825
忘了有多久
忘了有多久 2020-12-03 10:52

I have that code:

arr = arr.sort(function (a, b) {
    return a.time>b.time
})

Do I need to redefine arr or it is possible just to call

相关标签:
3条回答
  • 2020-12-03 11:10

    Use slice() to sort a copy of the original array.

    var arr =[{time:4},{time:3},{time:6}];
    
    arr.sort(function (a, b) {
      return a.time-b.time;
    });
    

    will mutate the original array and returns :

    [ { time: 3 }, { time: 4 }, { time: 6 } ]

    and console.log(arr) returns

    [ { time: 3 }, { time: 4 }, { time: 6 } ]

    but

    var arr =[{time:4},{time:3},{time:6}];
    arr.slice().sort(function (a, b) {
      return a.time-b.time;
    });
    

    returns

    [ { time: 3 }, { time: 4 }, { time: 6 } ]

    but will not affect the original array.

    console.log(arr) returns

    [ { time: 4 }, { time: 3 }, { time: 6 } ]

    0 讨论(0)
  • 2020-12-03 11:27

    It sorts the array in place (modifying the array). From MDN:

    The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

    0 讨论(0)
  • 2020-12-03 11:34

    It's a decent question, and let's answer it properly:

    const a = [1, 2, 3];
    const b = a.sort();
    console.log(a === b); // true
    

    there is your answer. The === operator for objects will compare memory locations, so it's the same object in memory.

    Which is a shame because it would be better if sort created a new array (immutability etc), but in many languages it does not return a new array, but the same array (reordered).

    So if you want it to be immutable, you can do:

    const a = [1, 2, 3];
    const b = a.slice(0).sort();
    
    0 讨论(0)
提交回复
热议问题