Sorting Arrays in JavaScript: toSorted() and sort()
javascript - How can I sort an array of integers? - Stack Overflow
array.sort() Does Not Simply Sort Numbers in JavaScript
Your Point 2 is valuable. Most sorting tutorials I see jump immediately to .sort((a, b) => a - b) for sorting numbers, without explaining how we get there.
You start with a description of what a return value of a positive number, negative number, or zero means, show an example of how we'd write out a longform sort function, and then lead to the shortcut, demonstrating that it will return a positive number, negative number, or zero.
More on reddit.comWhy does JavaScript sort integers this way?
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
Documentation:
Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Infinity - Infinity is NaN, not 0).
Also examples of sorting objects by key.
Just building on all of the above answers, they can also be done in one line like this:
var numArray = [140000, 104, 99];
numArray = numArray.sort(function (a, b) { return a - b; });
//outputs: 99, 104, 140000