Edited with additional info:
My apologies, but the shortest answer for this question is just:
function sort() {
var ary = [2, 1, 0.4, 2, 0.4, 0.2, 1.5, 1, 1.1, 1.3, 1.2, 0.2, 0.4, 0.9];
// use custom compare function that sorts numbers ascending
alert(ary.sort(function(a, b) {
return a - b;
}));
}
sort();
Note that if a compare function is not supplied to the sort
method, elements are sorted by converting them to strings and comparing strings in Unicode code point order. So [1, 2, 10].sort()
produces [1, 10, 2]
because "10"
, as a string, comes before "2"
. The code above will return the array sorted from smallest to largest correctly.
You can sort largest to smallest (descending order) by reversing a and b within the return
statement:
function (a, b) {
return b - a;
}