sort method in array

neo_vi's Avatar, Join Date: Feb 2008
Invasive contributor
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's Avatar, Join Date: Apr 2005
Team Leader
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's Avatar, Join Date: Apr 2005
Team Leader
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;
}