How to sort strings in JavaScript

后端 未结 12 2183
生来不讨喜
生来不讨喜 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条回答
  •  旧时难觅i
    2020-11-22 13:31

    You should use > or < and == here. So the solution would be:

    list.sort(function(item1, item2) {
        var val1 = item1.attr,
            val2 = item2.attr;
        if (val1 == val2) return 0;
        if (val1 > val2) return 1;
        if (val1 < val2) return -1;
    });
    

提交回复
热议问题