How to sort associative array in javascript?

I need to sort an associative JS array for one of my projects. I found this function that works fine in firefox, but unfortunately it doesn’t work in IE8, OPERA, CHROME ... I can’t find a way to make it work in other browsers or find another function that matches 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; } 
+4
source share
3 answers

It's impossible. Object in JavaScript (this is what you use as your "associative array") is indicated as not having a specific order when repeated with its properties using a for...in loop. You may observe some prevalence between the behavior of some browsers, but it is not universal .

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

+5
source

I know this old post, but this work:

problem

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

because the sort function takes 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; }); 
+1
source

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.

0
source

All Articles