Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/forums/javascript/)
-   -   sort method in array (http://www.go4expert.com/forums/sort-method-array-t15768/)

neo_vi 9Jan2009 10:54

sort method in array
 
In javascript, if we declare an array and sort it, it doesn't sort it as numbers, it always perform sort like strings.
for e.g
Code:

var array1={1,33,4,56,7,99,9};
array1.sort();
document.write(array1);

this wont return the correct result. how to perform a number sort.

pradeep 10Aug2009 11:13

Re: sort method in array
 
Code: JavaScript

var array1=[1,33,4,56,7,99,9];
array1.sort(sortNumber);
document.write(array1);
function sortNumber(a,b)
{
    return a - b;
}


pradeep 10Aug2009 11:13

Re: sort method in array
 
Reverse sort

Code:

var array1=[1,33,4,56,7,99,9];
array1.sort(sortNumber);
document.write(array1);
function sortNumber(a,b)
{
        return b - a;
}



All times are GMT +5.5. The time now is 05:00.