I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant find the way to make it work in other browsers, or find another function that would fit the purpose. I really appreciate any help.

function sortAssoc(aInput)
{
    var aTemp = [];
    for (var sKey in aInput) aTemp.push([sKey, aInput[sKey].length]);
    aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
    var aOutput = new Object();
    //for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
    for (var nIndex = 0; nIndex <= aTemp.length-1; nIndex++)
        aOutput[aTemp[nIndex][0]] = aInput[aTemp[nIndex][0]];
    //aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
    return aOutput;
}
share|improve this question
Where does it fail and what's the error message? – Frédéric Hamidi Oct 27 '10 at 10:37
Argh, my eyes! The formatting..! – andrewmu Oct 27 '10 at 10:40
There is no error message, it just do not sort array!! The array remain unsorted:( – Santi Oct 27 '10 at 10:56
Maybe this can help you: stackoverflow.com/questions/2466356/… – nekman Oct 27 '10 at 11:03
feedback

2 Answers

up vote 2 down vote accepted

This is impossible. An Object in JavaScript (which is what you're using as your "associative array") is specified as having no defined order when iterating over its properties using a for...in loop. You may be able to observe some common ground between some browsers' behaviour, but it's not universal.

Summary: if you need objects in a specific order, use an array.

share|improve this answer
Thank you. This may be really helpful. Try to find solution with array. – Santi Oct 27 '10 at 11:32
feedback

I know it's an old post but that work :

problem is

aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});

because the sort function attends a number :

aTemp.sort(function (a, b) {
    if (a[1] < b[1])
        return 1;
    else if (a[1] > b[1])
        return -1;
    else
        return 0;
});
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.