How to sort associative array in Javascript?
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;
}
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.
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;
});
I recently ran into this problem and found this question. I was disappointed to find that there was no pre-defined way to sort an associative array, but it made sense and pointed me in the right direction. I didn't fully realize that in JS associative arrays are really objects and are only arrays in name. I had an associative array that contained more associative arrays, ex:
var firstChild = {'id': 0, 'name': 'company Two'};
var secondChild = {'id': 1, 'name': 'company One'};
var parent = {
'company Two': firstChild,
'company One': secondChild
};
The following function will sort the above parent array based upon it's keys. For this to work as written, the parent array needs keys that match a value in the associated array. For instance, parent['unique string'] will need to have some key value that holds a value of 'unique string'. In my case, this is the name key; however, you can choose any key you like.
function associativeSort(givenArray, keyToSort) {
var results = [];
var temp = [];
for(var key in givenArray) {
temp.push(givenArray[key].name);
}
temp = temp.sort();
for(var x = 0; x < temp.length; x++) {
results[x] = givenArray[temp[x]];
}
return results;
}
Given my example array, this function would return:
var parent = {
'company One': {'id': 1, 'name': 'company One'},
'company Two': {'id': 0, 'name': 'company Two'}
};
It's a simple solution, but it took me a while to think of. Hope this helps others facing this problem.
精彩评论