Appearance
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
Output appears here after Run.
Or you can simplify the function:
Javascript array sort method
javascript
numberArray.sort((a, b) => a - b); // For ascending sort
numberArray.sort((a, b) => b - a); // For descending sortTIP
Use the sort() 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 sort() 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 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.