By default, the sort() function sorts values as strings, which is suitable for string comparisons (e.g., “Apple” comes before “Banana”).
However, when sorting numbers as strings, “25” would be considered greater than “100” because “2” is greater than “1”.
To address this issue, you can provide a comparison function to the sort() method.
Example
const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a – b}); |
Apply the same technique to sort an array in descending order.
Example
const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b – a}); |