views:

40

answers:

2

Hi, 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;
}

A: 

Sorry for formating, I tried to format it cca 10 minutes and have not find how to do it in onsite builded editor:( Why these pages do not support pure code?

Santi
A: 

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.

Tim Down
Thank you. This may be really helpful. Try to find solution with array.
Santi