I recently ran into this problem and found this question. I was disappointed that there was no predefined way to sort the associative array, but that made sense and pointed me in the right direction. I did not quite understand that in JS associative arrays are really objects and are only arrays by name. I had an associative array containing more associative arrays, for example:
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 sorts the above parent array based on its keys. For this to work as it is written, the parent array needs keys that match the value in the associated array. For example, parent ['unique string'] must have some key value that contains the value "unique string". In my case, this is the name key; however, you can choose any key that suits you.
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 sample array, this function will return:
var parent = { 'company One': {'id': 1, 'name': 'company One'}, 'company Two': {'id': 0, 'name': 'company Two'} };
This is a simple solution, but it took me a while to think. Hope this helps others facing this issue.
source share