PDA

View Full Version : Stupid number sorting question...


rsci
11-01-2002, 08:25 PM
Ok stupid number sorting question... I know this is an easy one, its just a Friday thing. How do I sort the array contents by value?

var newA=new Array("23", "2", "2", "1", "10", "16", "8");
newA.sort();
var kt="";
for (i=0; i<newA.length; i++) {
kt+=newA[i]+"\n";
}
alert(kt);

The script sorts the numbers but not by value, only by first digit so the results are:
1 10 16 2 2 23 8

Help?

Thanks,

RSCI

joh6nn
11-01-2002, 09:16 PM
var newA=new Array("23", "2", "2", "1", "10", "16", "8");
newA.sort(function(a,b) { return a - b; });
alert(newA.join('\n'));

the sort method of arrays, allows you to define your own function to sort them, meaning you can sort them in any manner you like. you can either use an unnamed function directly, like i did there, or create a separate function, and pass it's name to the sort() method, as an argument.

the functions for sorting, take two arguments, ( we'll call them a and b, but you can name them what you like ). if a should come before b in the array, then the function should return a value less than 0. if b should come before a, then the function should return a value greater than 0.

please note that returning a value of 0 will cause your computer to erupt in a horrible ball of fire and ash.

hope that helps.