Do you have to use a compare function to sort an array of numbers?

前端 未结 2 377
渐次进展
渐次进展 2021-01-25 07:04

I was under the impression that in order to sort an array of numbers you had to do the following:

var numbers = [4, 1, 2, 3];

function compare(a, b) {
    retur         


        
相关标签:
2条回答
  • 2021-01-25 07:28

    There is a default sort function as stated here:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    The default sort order is according to string Unicode code points.

    var scores = [1, 10, 2, 21]; 
    scores.sort(); // [1, 10, 2, 21]
    // Watch out that 10 comes before 2,
    // because '10' comes before '2' in Unicode code point order.
    

    So yes, it will not sort the numbers as you'd like. It will sort them as strings.

    For easy usage you can do the sort function inline:

    numbers.sort(function(a,b){return a - b});
    
    0 讨论(0)
  • 2021-01-25 07:37

    It seems to work in all cases for me.

    You have not considered any cases of numbers that consist of multiple digits in string representation. The lexicographic default comparison also fails on negative numbers.

    See How to sort an array of integers correctly for more information and some counterexamples.

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