so***********@yahoo.com wrote:
Hi
I have an associative array like this:
arr[x1]=30; arr[x2]=20;arr[x3]=40;arr[x4]=10;
I want the sort function to sort keys in ascending order of the values
on the right hand side with the following result:
x4,x2,x1,x3
Can anyone please help me write the function?
Thank you
<script language="JavaScript">
// create an array
var arr = [];
arr["x1"]=30;
arr["x2"]=20;
arr["x3"]=40;
arr["x4"]=10;
// show the current array
for (var sKey in arr)
document.write(sKey + ':' + arr[sKey] + '; ');
document.write('<br />');
// sort 'array'
var arr2 = sortAssoc(arr);
// show the sorted array
for (var sKey in arr2)
document.write(sKey + ':' + arr2[sKey] + '; ');
document.write('<br />');
// And here comes the funciton itself
function sortAssoc(aInput)
{
var aTemp = [];
for (var sKey in aInput)
aTemp.push([sKey, aInput[sKey]]);
aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
var aOutput = [];
for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
return aOutput;
}
</script>
Hope I helped you/
Sergey.