Sorting in [removed] Shouldn't returning a boolean be enough for a comparison function?

后端 未结 2 2005
南方客
南方客 2020-11-21 04:26

I have always successfully sorted my arrays like this (when I did not want the standard lexicographic ordering):

var arr = […] // some numbers or so
arr.sort         


        
2条回答
  •  执笔经年
    2020-11-21 05:14

    The sort function expects a function that expects two arguments a and b, and returns:

    • A negative number if a comes before b
    • A positive number if a comes after b
    • Zero if relative order of a and b does not matter

    In order to sort numbers in ascending order return a - b will produce the correct return values; for example:

    a    b    ret
    1    2    -1
    3    2     1
    2    2     0
    

    On the other hand return a > b produces the following return values:

    a    b    ret      implied
    1    2    false    0
    3    2    true     1
    2    2    false    0
    

    In the above example, the sort function is told that 1 and 2 are same (and placing 1 before 2 or 2 before 1 does not matter). This will produce incorrect result, for example (in Chrome 49):

    console.log([5, 8, 7, 1, 2, 3, 4, 6, 9, 10, 11, 12, 13].sort(function(a, b) {
        return a > b;
    }));
    // [4, 5, 3, 1, 2, 6, 7, 8, 9, 10, 11, 12, 13]

提交回复
热议问题