Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){…})

后端 未结 4 594
醉梦人生
醉梦人生 2021-02-02 03:12

I am trying to understand how exactly sort() works and how I am supposed to use it.

I did some research (google) and went through the similar questions here on stackover

相关标签:
4条回答
  • 2021-02-02 03:37

    First of all, you did a good research and covered almost all possible cases, and you can find the MDN documentation here

    You just missed the case of Sorting non-ASCII characters

    For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use String.localeCompare. This function can compare those characters so they appear in the right order.

    var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
    items.sort(function (a, b) {
      return a.localeCompare(b);
    });
    
    // items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
    
    0 讨论(0)
  • 2021-02-02 03:43

    I think, you would like to combine the sort criteria, like this example which sort by name forst and then by number. Please watch 'John'.

    var myArr = [{ "sortnumber": 9, "name": "Bob" }, { "sortnumber": 5, "name": "Alice" }, { "sortnumber": 4, "name": "John" }, { "sortnumber": 3, "name": "James" }, { "sortnumber": 7, "name": "Peter" }, { "sortnumber": 6, "name": "Doug" }, { "sortnumber": 2, "name": "Stacey" }, { "sortnumber": 14, "name": "John" }, { "sortnumber": 12, "name": "John" }];
    
    myArr.sort(function (a, b) {
        return a.name.localeCompare(b.name) ||  a.sortnumber - b.sortnumber;
    });
    
    console.log(myArr);

    0 讨论(0)
  • 2021-02-02 03:57

    Ok, so after some additional research, going through the MDN documentation, and the arraysort and arraysort2 links, which I found very helpful, I created a slide that could probably be of use to someone else, so I am posting it here. Thank you all for your answers!

    0 讨论(0)
  • 2021-02-02 04:04

    According to Array reference (http://www.w3schools.com/jsref/jsref_sort.asp):

    By default, the sort() method sorts the values as strings in alphabetical and ascending order.

    So your first understanding about sort() is correct. However, the second and third are not yet correct. First of all, they are both the same case, which is providing a sorting function to the sort() method. This method should compare the a and b, and return negative, zero, or positive values, indicating if a is less than, equals, or greater than b. So for example, you can still compare your myArr using the name property like this:

    myArr.sort(function(a,b) {
      return a.name.localeCompare(b.name);
    });
    
    0 讨论(0)
提交回复
热议问题