Is this Possible?!? Sorting a 2 dimensional Jscrip

# Thread: Is this Possible?!? Sorting a 2 dimensional Jscrip

1. Member
Join Date
Dec 1969
Posts
38

## Is this Possible?!? Sorting a 2 dimensional Jscrip

Hi all.<BR><BR>This is a tough one. I have 2 dimensional jscript array. (an array with another array in each cell)<BR><BR>I need to sort this on 2 different indexes. Basically, for instance, if the array contents are like this:<BR><BR>bill &#124 15 &#124 0.326 &#124 82 &#124 (-41) &#124 <BR>billy &#124 10 &#124 0.217 &#124 138 &#124 (+15) &#124 <BR>ceejay &#124 12 &#124 0.261 &#124 68 &#124 (-55) &#124 <BR><BR>I need to sort this based on the first numeric value descending, and also sub-sort? it by the last number. So if 2 people have the same first number, it then sorts uner that for the second.<BR><BR>Does that make any sense?<BR><BR>Basically, I want to mimic the way you can order by 2 columns in SQL.<BR><BR>b<BR>

2. Senior Member
Join Date
Dec 1969
Posts
96,118

## Not a tough one, at all.

You have to pass a function to the sort() method and then that function has to compare a pair of elements (in this case, the "inner" arrays) and decide which is bigger.<BR><BR>If you read the docs on Array.sort you&#039;ll see more info.<BR><BR>*PROBABLY* something like this, for you (assuming I understood the data you gave us):<BR><BR>function MyCompare( e1, e2 )<BR>{<BR> // compare first numeric values, first<BR> if ( e1[1] &#060; e2[1] ) return -1;<BR> if ( e1[1] &#062; e2[1] ) return 1;<BR> // values are same, compare on last numbers<BR> if ( e1[4] &#060; e2[4] ) return -1;<BR> if ( e1[4] &#062; e2[4] ) return 1;<BR> return 0; // truly equal<BR>}<BR><BR>And then you simply do:<BR><BR> myArray.sort( MyCompare );<BR><BR><BR>Presto.<BR><BR>If you want to see a demo of this in action, look at my "sorting in the browser" demo at<BR>http://www.ClearviewDesign.com/NEWBIE<BR><BR><BR>

3. Member
Join Date
Dec 1969
Posts
38

## RE: Not a tough one, at all.

Bill,<BR><BR>Right there in my face the whole time. I actually, did not really grasp how to use the .sort function to do sorting on more than one dimension. This made it crystal clear, and it works like a charm.<BR><BR>I can&#039;t thank you enough.<BR><BR>Bill

4. Senior Member
Join Date
Dec 1969
Posts
96,118

## Don't thank me...

...thank the people who invented JS and put that neat feature into Array.sort !!<BR><BR>And, hey, *anything* is obvious once you see it done.<BR><BR>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•