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

后端 未结 4 597
醉梦人生
醉梦人生 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é']
    

提交回复
热议问题