Sunday, 27 October 2019

Array - sort simple numerical values

The following Google Apps Script is designed to take an array of numerical items and sort them in ascending order (from lowest to highest).

We begin with an array of values and call a function named sortNumbers.
var myArray = [40, 100, 1, 5, 25, 10];
myArray.sort(sortNumbers);
The sortNumbers function takes 2 values as input parameters and sorts them according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes are done with the sort order of the two values.
function sortNumbers(a, b) {
  return a - b;
}
So in this example we end up with the result.
[1.0, 5.0, 10.0, 25.0, 40.0, 100.0]
Here is a link to a version with a 2-D array of items each with a value.

Array sort numerical values.gs

No comments:

Post a Comment