How to Sort an Array of Integers

The sort() method sorts the arrays alphabetically. However, you can also use it for sorting an array of integers.

To sort numerically, you should add a new method which handles numeric sorts:

Javascript array sort method
function sortNumber(a, b) { return a - b; } let numberArray = [170000, 65, 154]; numberArray.sort(sortNumber); console.log(numberArray);

Or you can simplify the function:

numberArray.sort((a, b) => a - b); // For ascending sort
numberArray.sort((a, b) => b - a); // For descending sort
Use the sort() function if the compared arrays do not contain Infinity or NaN.

Comparing two values, the sort() sends the values to the compare function and sorts the values according to the returned value (negative, positive or).

  • If the returned value is negative a is sorted before b.
  • If the returned value is positive b is sorted before a.
  • If the result is 0 nothing changes.

When comparing, for example, 30 and 100, the sort() method calls the compare function(30, 100). The function calculates 30 - 100 (a - b), and since the result is negative (-70), the sort function will sort 30 as a value lower than 100.