Need Help Sorting a JavaScript Array ... ????

T

Tommo

Hello All,
whilst I know how to sort an array I am having problems with
my situation, what I would ideally like is something like a 'sort
keys' action with Perl hashes.
I am reading in data and building an array entry that will
be of the form:-
array[0] - horse1,2,4,6,1,3,6 = 22
...
array[6] - horse6,2,3,6,1,9,8 = 29
etc etc.

I know want to sort these array entries based on the totals (i.e 22,
29 etc), I figured you cannot do this in one array so maybe 2 arrays,
one array would be as follows:-
array1[0] - horse1,2,4,6,1,3,6 =
...
array1[6] - horse6,2,3,6,1,9,8 =

and the second array:-
array2[0] - 22
...
array2[6] - 29

I could then sort on the 2nd array, the trouble is that I loose the
relationship between the 2 arrays.

I thought about creating an object array to sort upon but am unsure if
this would work. Has anyone a solution to this and if so some example
code to help me along.

thanx, Mark ....
 
T

Tommo

thanks for your assistance, I will also do some testing and post back results ..

cheers, Mark ..
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
whilst I know how to sort an array I am having problems with
my situation, what I would ideally like is something like a 'sort
keys' action with Perl hashes.
I am reading in data and building an array entry that will
be of the form:-
array[0] - horse1,2,4,6,1,3,6 = 22
...
array[6] - horse6,2,3,6,1,9,8 = 29
etc etc.


You can use the sort method of the outer array by providing it with a
suitable compare function.

function Compare(X, Y) { var SX = SY = 0
for (J=1; J<X.length; J++) SX += X[J] // form score
for (J=1; J<Y.length; J++) SY += Y[J] // form score
return SY - SX }

That is probably about right; it should return the difference between
the scores of the two horses. If X.length = Y.length always, the loops
can merge; otherwise, the job seems unfair.

For efficiency, though, the sums should be calculated once per horse;
and, as someone said, if they are placed at the start of the data
structure the default sort could suffice.

To use sort keys in general, just provide a compare function that
compares them appropriately, returning <0, 0, >0 accordingly.

Consider representing each animal as

Nag = {Score:22, Name:"Shergar", Data:[2,4,6,1,3,6]}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top