Search code examples
arraysstringsortingobjectjscript

jscript: wrong sort behavior?


I'm trying to sort multi-level object by value in 'st' property of each element:

var     aMyArr = [
        {
            "st" : "ISMTP"
        }, , {
            "st" : "IFTP"
        }, {
            "st" : "I"
        }
    ];


for (i in aMyArr){
    WScript.Echo(aMyArr[i].st);
}

aMyArr.sort(sortBySt);


for (i in aMyArr){
    WScript.Echo(aMyArr[i].st);
}


function sortBySt(param1, param2){
    var ret = 0;
    if (param1.st.toLowerCase() > param2.st.toLowerCase())
        ret = 1;

    if (param1.st.toLowerCase() < param2.st.toLowerCase())
        ret = -1;

    WScript.Echo(param1.st+" > "+param2.st+" ==> "+ret);
    return ret
}

Of course the real structure of aMyArr is much more complex, it is simplified for this question.

The output is quite unexpected:

ISMTP  // before sorting
IFTP
I

IFTP > I ==> 1
IFTP > ISMTP ==> -1
IFTP > I ==> 1

I      // after sorting
ISMTP
IFTP

Whilst I expect just in alphabetical order. As far as I understand it may happen because aMyArr is not pure array but object but this doesn't explain two IFTP > I comparations.

Is there any way to sort it properly?


Solution

  • Change:

    var     aMyArr = [
            {
                "st" : "ISMTP"
            }, , {
                "st" : "IFTP"
            }, {
                "st" : "I"
            }
        ];
    

    to

    var     aMyArr = [
            {
                "st" : "ISMTP"
            }, {
                "st" : "IFTP"
            }, {
                "st" : "I"
            }
        ];
    

    (mark the deletion of " ,")