how can I make my json array sort function case insensitive?

后端 未结 2 331
渐次进展
渐次进展 2021-01-28 08:32

I have the following fiddle that is my attempt at

  • taking a json array
  • sort the array by the displayname value
  • add the sorted array to the DOM as
相关标签:
2条回答
  • 2021-01-28 09:04

    Use the function toLowerCase() and convert to string with + ""

    myArray.jsonData.sort(function(a, b) {
       var comp = ((a[prop]+"").toLowerCase() >
                   (b[prop]+"").toLowerCase()) ? 1 : -1 ;
       return asc ? comp : -comp;
    });
    
    0 讨论(0)
  • 2021-01-28 09:04

    If you are always sorting strings, you can use:

    function(a,b){
       return a.toLowerCase() > b.toLowerCase();
    }
    

    which in your example would be:

    myArray.jsonData.sort(function(a,b){
        var result, 
            av=a[prop].toLowerCase(), 
            bv=b[prop].toLowerCase();
        return asc ? av > bv : av < bv;
    }
    
    0 讨论(0)
提交回复
热议问题