Forum Moderators: open

Message Too Old, No Replies

Sort By Number In String

Not Having Much Luck

         

theriddla1019

4:18 pm on Oct 12, 2004 (gmt 0)

10+ Year Member



Im trying to sort an array that is a split up textfield. The array values will basicly look like this
ec_array[0] 1. text text text text text
ec_array[1] 2. more text more text more
ec_array[2] 5. etc etc etc etc etc etc
ec_array[3] 10. more more more more more

Now of course the normal javascript sort function is putting these in order 1, 10, 2, 5. So i saw the bubblesort, with the same results, then tried the
sort(compareNumbers)
function compareNumbers(a,b){return a - b}
which just doesnt work
then tried
function compare(a, b) {
if (a < b)
return -1
if (a > b)
return 1
}
which works the exact same way as just plain sort.

Now im assuming im having problems with compareNumbers because their is more than just a number for each array value. Is there a way to do this that will see the number at the beginning of the array value and sort it numerically?
My current script looks like this:

function compare(a, b) {
if (a < b)
return -1
if (a > b)
return 1
}

function array_builder(){
ec_array = "";
ecstring = document.add.episodecomments.value;
ec_array = ecstring.split("-");
count = 0;
ecstring = "";
ec_array.sort(compare);
while (count < ec_array.length){
if(count > 0){
ecstring+= "-" + ec_array[count];
} else {
ecstring+= ec_array[count];
}
count+=1;
}
alert ec_array;
document.add.episodecomments.value = ecstring;
}

Thanx!

Rambo Tribble

2:43 am on Oct 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You need to use parseInt() to convert your strings to numbers before you apply the sort (with the function that does the numerical comparison).

dcrombie

3:49 pm on Oct 14, 2004 (gmt 0)



Does this work?

function compare(a, b) { 
return intval(a) < intval(b);
}

;)