Numeric Sorting with Google Apps Script
By default, the sort method sorts an array alphabetically, so numbers are sorted based on their characters:
let arr = [5, 300, 30.9, 35, 3];
arr.sort();
console.log(arr); // Returns: [3, 30.9, 300, 35, 5]
Ascending Numeric Sort
To perform numeric sorting, define the comparison function for the sort method:
let arr = [5, 300, 30.9, 35, 3];
arr.sort((a, b) => a - b);
console.log(arr); // Returns: [3, 5, 30.9, 35, 300]
In this case, numbers are sorted based on their value, not their characters.
If a - b is replaced with a > b, it also works here because all values in the array are numbers. But if these numbers were in text format, a > b would perform an alphabetical sort, so it's better to use a - b.
Descending Numeric Sort
To perform a descending sort, simply replace a - b with b - a to reverse the order of sorting:
let arr = [5, 300, 30.9, 35, 3];
arr.sort((a, b) => b - a);
console.log(arr); // Returns: [300, 35, 30.9, 5, 3]