W3docs

How to Sort an Array of Integers

Read this JavaScript tutorial and learn useful information about the logic of the sort() method which will help you sort an array of integers correctly.

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

javascript— editable

Or you can simplify the function:

Javascript array sort method

numberArray.sort((a, b) => a - b); // For ascending sort
numberArray.sort((a, b) => b - a); // For descending sort
Tip

Use the <kbd class="highlighted">sort()</kbd> function if the compared arrays do not contain Infinity or NaN.

Warning

Note: The sort() method mutates the original array in place and returns the sorted array.

Comparing two values, the <kbd class="highlighted">sort()</kbd> sends the values to the compare function and sorts the values according to the returned value (negative, positive, or zero).

  • 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 <kbd class="highlighted">sort()</kbd> 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.