Forum Moderators: open

Message Too Old, No Replies

Sorting Arrays

sorting an myArray[i].stuff = n array

         

proper_bo

10:38 am on May 18, 2006 (gmt 0)

10+ Year Member



I am far from good at javascript. I started learning it to customise google maps api and so here I am, asking for help again.

I have an array:

var myArray = [];
myArray[0].stuff = 23;
myArray[1].stuff = 45;
myArray[2].stuff = 41;
myArray[3].stuff = 29;
myArray[4].stuff = 36;

I would like to organise the array so it looks like:
myArray[0].stuff = 23;
myArray[3].stuff = 29;
myArray[4].stuff = 36;
myArray[2].stuff = 41;
myArray[1].stuff = 45;

I can then loop through it. Joy.

How so I do this?

Thank you.

jshanman

1:08 pm on May 18, 2006 (gmt 0)

10+ Year Member



You can do this 2 ways. You can use your own sorting algorithm, or you can use the built in array sort method.

Method 1: do a google search for "javascript quicksort".

Method 2:
//given an array of objects
var myArray = new Array();
myArray[0] = new Object();
myArray[0].stuff = 23;
myArray[1] = new Object();
myArray[1].stuff = 45;
myArray[2] = new Object();
myArray[2].stuff = 41;
myArray[3] = new Object();
myArray[3].stuff = 29;
myArray[4] = new Object();
myArray[4].stuff = 36;

var sortArray = new Array();
var objHolder = new Object();

//copy .stuff values into sortArray
//copy objects into objHolder using o + .stuff as the index (so objHolder.o36 == myArray[x].stuff == 36)
for (i in myArray) {
sortArray[i] = myArray[i].stuff;
objHolder["o"+myArray[i].stuff] = myArray[i];
}

sortArray.sort();//use the javascript sort method
//sortArray.reverse(); //even reverse if you want to

//repopulate myArray with the objects in desired order.
for (i in sortArray) {
myArray[i] = objHolder["o"+sortArray[i]];
}

- JS

proper_bo

1:25 pm on May 18, 2006 (gmt 0)

10+ Year Member



Hi Js and thanks,

There seems to be a small problem though.

It is ordering like so: (example 12 entries)

myArray[0]
myArray[1]
myArray[11]
myArray[12]
myArray[2]
myArray[3]
...

Is there a way to deal with 2 and even three digit keys?

jshanman

1:30 pm on May 18, 2006 (gmt 0)

10+ Year Member



I forgot that the .sort method sorts alpha. To get it to sort numerical, try this function (copied from: [javascriptkit.com...]

function sortit(a,b){
return(a-b)
}

myArray.sort(sortit);

See if that works!

- JS

proper_bo

1:32 pm on May 18, 2006 (gmt 0)

10+ Year Member



bingo. Thanks.