The following Google Apps Script builds on
this previous blog post by introducing sorting for a 2-D array that contains items with a numerical value. As before we want to sort the array in ascending order based on the numerical value, but also keep the text associated with it (which in this example is part of a larger script that counts the frequency of words in a piece of text).
var myArray = [["means", 5.0], ["you’ve", 3.0], ["help", 19.0], ["they", 17.0]];
All we ultimately need to do in the
sortNumbers function is define which part of the array the '
sort' needs to look at. As an array starts at zero that would give us the text value which is not what we want, so instead we specify that
a and
b should use position one for the numerical value. In this example we have logged the value to verify the correct element of the array is being called.
function sortNumbers(a, b) {
Logger.log(a[1]);
Logger.log(b[1]);
return a[1] - b[1];
}
So in this example we end up with the result.
[[you’ve, 3.0], [means, 5.0], [they, 17.0], [help, 19.0]]