How to sort strings in JavaScript

后端 未结 12 2053
生来不讨喜
生来不讨喜 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:27

    In your operation in your initial question, you are performing the following operation:

    item1.attr - item2.attr
    

    So, assuming those are numbers (i.e. item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. The following should work:

    return parseInt(item1.attr) - parseInt(item2.attr);
    

    If they are alphaNumeric, then do use localCompare().

    0 讨论(0)
  • 2020-11-22 13:28
    list.sort(function(item1, item2){
        return +(item1.attr > item2.attr) || +(item1.attr === item2.attr) - 1;
    }) 
    

    How they work samples:

    +('aaa'>'bbb')||+('aaa'==='bbb')-1
    +(false)||+(false)-1
    0||0-1
    -1
    
    +('bbb'>'aaa')||+('bbb'==='aaa')-1
    +(true)||+(false)-1
    1||0-1
    1
    
    +('aaa'>'aaa')||+('aaa'==='aaa')-1
    +(false)||+(true)-1
    0||1-1
    0
    
    0 讨论(0)
  • 2020-11-22 13:28
    <!doctype html>
    <html>
    <body>
    <p id = "myString">zyxtspqnmdba</p>
    <p id = "orderedString"></p>
    <script>
    var myString = document.getElementById("myString").innerHTML;
    orderString(myString);
    function orderString(str) {
        var i = 0;
        var myArray = str.split("");
        while (i < str.length){
            var j = i + 1;
            while (j < str.length) {
                if (myArray[j] < myArray[i]){
                    var temp = myArray[i];
                    myArray[i] = myArray[j];
                    myArray[j] = temp;
                }
                j++;
            }
            i++;
        }
        var newString = myArray.join("");
        document.getElementById("orderedString").innerHTML = newString;
    }
    </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 13:29

    An explanation of why the approach in the question doesn't work:

    let products = [
        { name: "laptop", price: 800 },
        { name: "phone", price:200},
        { name: "tv", price: 1200}
    ];
    products.sort( (a, b) => {
        {let value= a.name - b.name; console.log(value); return value}
    });
    
    > 2 NaN
    

    Subtraction between strings returns NaN.

    Echoing @Alejadro's answer, the right approach is--

    products.sort( (a,b) => a.name > b.name ? 1 : -1 )

    0 讨论(0)
  • 2020-11-22 13:30
    var str = ['v','a','da','c','k','l']
    var b = str.join('').split('').sort().reverse().join('')
    console.log(b)
    
    0 讨论(0)
  • 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;
    });
    
    0 讨论(0)
提交回复
热议问题