How to sort an array of integers correctly?

Posted by Ramesh Singh | Updated on

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) –

In ES6, you can simplify this with arrow functions:

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don’t contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers