How to sort strings in JavaScript

后端 未结 12 2056
生来不讨喜
生来不讨喜 2020-11-22 13:20

I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    retur         


        
12条回答
  •  长情又很酷
    2020-11-22 13:46

    Use String.prototype.localeCompare a per your example:

    list.sort(function (a, b) {
        return ('' + a.attr).localeCompare(b.attr);
    })
    

    We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:

    if (item1.attr < item2.attr)
      return -1;
    if ( item1.attr > item2.attr)
      return 1;
    return 0;
    

提交回复
热议问题