473,729 Members | 2,149 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting an associative array keys based on values

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

Jul 23 '05 #1
5 37709
so***********@y ahoo.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="JavaS cript">
// 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(aInpu t)
{
var aTemp = [];
for (var sKey in aInput)
aTemp.push([sKey, aInput[sKey]]);
aTemp.sort(func tion () {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.

Jul 23 '05 #2
so***********@y ahoo.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


If you can guarantee unique numeric keys on the right...

function assocSort (oAssoc) {
var idx; var key; var arVal = []; var arValKey = []; var oRes = {};
for (key in oAssoc) {
arVal[arVal.length] = oAssoc[key];
arValKey[oAssoc[key]] = key;
}
arVal.sort();
for (idx in arVal)
oRes[arValKey[arVal[idx]]] = arVal[idx];
return oRes;
}

var arr = {x1:30, x2:20, x3:40, x4:10}
var arrSorted = assocSort(arr);
Csaba Gabor from Vienna

Jul 23 '05 #3
VK
> I have an associative array
Thank you for your perfect language
;-) :-|
I want the sort function to sort keys
in ascending order of the values


(1) First of all, you may want to use the standard associative array
syntacs for predefined values (given that x1...x4 are real variables in
your script)

var map = { x1 : 30, x2 : 20 , x3 : 40, x4 : 10};

(2) JavaScript doesn't have an associative array as a programming
entity. So any more or less complicated operations over an associative
array have to be programmed manually by yourselve. In your case there
is no way (?) to accomplish that w/o multiple pass over the hash
table.
To be continued... (if you still need it)

Jul 23 '05 #4
so***********@y ahoo.com writes:
I have an associative array like this:
arr[x1]=30; arr[x2]=20;arr[x3]=40;arr[x4]=10;
I guess you have
var arr = new Object();
or something, as well as the variables x1..x4 declared.
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
I assume values are always numbers. Otherwise a less trivial
comparison function is needed.

function sortByValue(key Array, valueMap) {
return keyArray.sort(f unction(a,b){re turn valueMap[a]-valueMap[b];});
}

testing:

var arr = {foo: 30, bar: 20, baz:40, doh: 10};
var keyArray = ["foo","bar","ba z","doh"]
alert(sortByVal ue(keyArray, arr));
Can anyone please help me write the function?


There you go.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5
Lasse Reichstein Nielsen wrote:
so***********@y ahoo.com writes:

I have an associative array like this:
arr[x1]=30; arr[x2]=20;arr[x3]=40;arr[x4]=10;

I guess you have
var arr = new Object();
or something, as well as the variables x1..x4 declared.


I may have read it wrong but I read it as more like arr['x1'] where the
quotes were forgotten. If the sort is to be done by strings (if they are
indeed strings) then its a simple matter of .sort() and .reverse().

If the sort is based on the value of the variables, then you wouldn't
always get the order x4, x3, x2, x1 unless you grab the variable name
itself and create your own list and then sort and reverse it.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
18892
by: Leonardo | last post by:
I have the following associative array: $user=1; $user=1; $user=0; $user=1; $user=0; $user=1; $user=1;
1
4436
by: noah | last post by:
Can anyone think of a way to make array keys case insensitive? An option on any recent PHP would be to convert all array keys to lowercase using the standard array_change_key_case() function. As it turns out, I'm stuck on a PHP 4.1.3 system, so that function is not available to me. Can anyone think of an efficient way to write my own version of this function? Can I edit keys in place without copying the values, or will I have to copy the...
2
1551
by: Zenobia | last post by:
I have a problem. I need to look up several values stored in arrays. Each value is stored as a pair. The first (number) represents the probability of this item occurring. For instance, in the example below there are 11 items. conFinal = {2:'m',4:'n',6:'ng',8:'r',10:'l',12:'kh',14:'k',16:'s',18:'hl',19:'tl',20:'sh'} Letter 'n' (2nd item) has a probability of 2 chances in 20 (1 in 10] but 'tl' has only a 1 in 20 chance. The chance is
6
2017
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference between London and the previous element is 25 (40-15), London has a 25% chance of being selected. When I call the function getAssocItem to do this I need to send in 2 arguments. Is there a quick way to get the maximum key value in the associative
2
10245
by: Remi Bastide | last post by:
Is is possible to initialize a javascript associative array inline, as you would do in PHP, e.g. : <?php $a = array("abc" => "def", "ghi" => "jkl"); ?>
47
5081
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they are not at all. If you are doing *array", then you have to use only integer values for array index, as it was since ALGOL.
11
30972
by: Angus Comber | last post by:
Hello I want to create a lookup table where I can store string keys: For example: 192.168.0.1 -> Purple 192.168.0.2 -> Blue 192.168.0.3 -> Red
3
6757
by: Matthias Heise | last post by:
Hello, how can I walk through an associative Array in C#? example array: int arr = new Array(); int = 5; int = 10; ....
2
3412
by: ctj951 | last post by:
What I am trying to do is implement a associative array to lookup data based on a key in C. This might simple to do in C++ but I'm restricted to use C. The size of the data for the table isn't too large but too large to structure the code as a clean chain of if/else or similar logic. Also, the lookup key values can be large, unpredictable and not well dispersed which doesn't suit itself to a hash table. OK so my current idea for...
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.