Recently when I was working with JavaScript \"sort()\" function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbe
And what if your n is defined as:
var n = [10, 5, 40, 25, 100, 1];
Well, if you are sorting the following list, it contains only strings:
var n = ["10", "5", "40", "25", "100", "1"];
So I would expect any language would compare them as strings, thus resulting in a sort order of:
var n = ["1", "10", "100", "25", "40", "5"];
Which necessitates your code to use a custom sort (as you have done) to cast the strings back to integers for the purposes of sorting.
Edit
As Pointy mentioned, by default the JavaScript sort() method sorts elements alphabetically, including numbers:
By default, the sort() method sorts the elements alphabetically and ascending. However, numbers will not be sorted correctly (40 comes before 5). To sort numbers, you must add a function that compare numbers.
Simply amazing... so a custom sort is required even for an array of integers.