I was under the impression that in order to sort an array of numbers you had to do the following:
var numbers = [4, 1, 2, 3];
function compare(a, b) {
retur
There is a default sort function as stated here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The default sort order is according to string Unicode code points.
var scores = [1, 10, 2, 21];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
So yes, it will not sort the numbers as you'd like. It will sort them as strings.
For easy usage you can do the sort function inline:
numbers.sort(function(a,b){return a - b});
It seems to work in all cases for me.
You have not considered any cases of numbers that consist of multiple digits in string representation. The lexicographic default comparison also fails on negative numbers.
See How to sort an array of integers correctly for more information and some counterexamples.