The Array method sort() in Apps Script
The Array method sort()
sorts the elements in an array in place and returns a reference to the sorted array.
Prerequisites
This tutorial assumes that you're familiar with:
Basic Apps Script concepts such as:
Strings
Functions
How to create and run simple Apps Script scripts using the script editor in Google Sheets.
How it worksDefault sorting behavior
By default, the sort()
function converts all the values in the array into strings and then sorts these strings in ascending order.
function sortArr() {
var arr = [9, 2,1,7,5];
//By default, the sort() function will sort the array in ascending order.
Logger.log(arr.sort());
//Output: [1.0, 2.0, 5.0, 7.0, 9.0]
}
This behavior could result in weird results. For example, take the following array containing numbers: [20, 10, 30, 4]
. When you sort this array, the output you'd expect is [4, 10, 20, 30]
but the actual result is [10, 20, 30, 4]
. How can 4 be greater than 10, 20 and 30? This weird result is a consequence of the fact that the array's elements are converted to strings before being sorted. Since string comparison proceeds character by character, strings that start with "4" will be sorted after strings that start with "1", "2" or "3".
Similarly, you might get weird results when sorting other non-string values.
Overriding the default sorting behavior
The good news is that you don't have to rely on the default sorting behavior. You can write your own function that will sort the array just the way you want it. Here is an example of a comparison function to sort an array in descending order:
function descOrder(element1, element2) {
if(element1 > element2)
return -1; //Sort element1 before element2
if(element1 < element2)
return 1; //Sort element1 after element2
return 0; //Don't change the positions of element1 and element2
}
To use it, pass this comparison function as a parameter to the sort()
method.
function sortDescending() {
var arr = [9, 2,1,7,5];
//You can specify a custom sort function that will sort the array in descending order.
Logger.log(arr.sort(descOrder));
}
Output: [9.0, 7.0, 5.0, 2.0, 1.0]
Syntaxarray.sort(compareFunction)
Parameters
array.sort(compareFunction)
optional compareFunction(element1, element2)
compareFunction (or comparison function) is an optional parameter that can be used to change the default sorting order in the sort()
function. A few use cases where you might use a comparison function are:
Sorting an array in descending order (default is ascending).
Sorting an array containing numeric values.
Sorting an array containing objects.
Sorting an array containing strings using a specific language's conventions. This is especially useful when dealing with text in other languages.
The comparison function compares two elements (element1 and element2) at a time and returns:
A number > 0 if element2 must be sorted before element1
A number < 0 if element1 must be sorted before element2
0 if element1 and element2 are equal and hence their order in the array relative to each other can stay the same
Please see the examples below to understand when and how to use a comparison function.
Return value
The sort()
method sorts an array and returns a reference to it.
⚠ Warning
The sort()
method sorts an array in place. This means that the array the sort()
method is called on will itself be sorted and a reference to it will be returned. This behavior will become clear when you read the examples below.
ExamplesIn Apps Script, you can only run functions. So you have to copy and paste each of the code snippets below into a function before you run them.
I recommend creating separate functions to try out each of the examples below. Also, don't forget to give each of these functions a unique name.
Example 1: The sort() method sorts an array in place
In Apps Script, you can only run functions. So you have to copy and paste each of the code snippets below into a function before you run them.
I recommend creating separate functions to try out each of the examples below. Also, don't forget to give each of these functions a unique name.
In the code below, the array colors
is sorted in ascending order. Please note that the sort()
method sorts the array in place - i.e., the colors
array is itself sorted.
var colors = ["red", "blue", "green", "black", "orange", "purple"];
colors.sort();
Logger.log(colors);
Output
[black, blue, green, orange, purple, red]
Example 2: The sort() method returns a reference to the array that was reversed
The sort()
method does not return a new array. It returns a reference to the array that was sorted. This is an important concept to understand to ensure your code does not result in unintended consequences.
For example, In the code below, the variable sortedColors
contains a reference to the sorted
array. It is not a new array. So, by adding a new item to the sortedColors
array, you're actually adding an item to the colors
array. This may not have been your intention and this behavior could lead to unintended consequences or bugs in your program.
var colors = ["red", "blue", "green", "black", "orange", "purple"];
var sortedColors = colors.sort();
Logger.log(colors);
Logger.log(sortedColors);
Logger.log(colors === sortedColors);
//Add an item to the sortedColors array
sortedColors.push("indigo");
Logger.log(colors);
Logger.log(sortedColors);
Output
[black, blue, green, orange, purple, red]
[black, blue, green, orange, purple, red]
true
[black, blue, green, orange, purple, red, indigo]
[black, blue, green, orange, purple, red, indigo]
Example 3: Sorting an array of numbers in ascending order
Like mentioned earlier in this tutorial, you should be careful when sorting an array of numbers using the sort()
method. This is because the default sorting could result in unexpected results since the numbers will be converted to strings before being sorted. For example, the number 10 will be sorted before the number 2.
★ Important
Always specify a comparison function when sorting numbers to ensure expected sorting behavior.
function compareNumbers(num1, num2) {
if(num1 > num2)
return 1;
if(num1 < num2)
return -1;
return 0;
}
function sortNumbers() {
var numbers = [1,5,2,10,7,20,3];
Logger.log(numbers);
Logger.log(numbers.sort(compareNumbers));
}
Output
[1.0, 5.0, 2.0, 10.0, 7.0, 20.0, 3.0]
[1.0, 2.0, 3.0, 5.0, 7.0, 10.0, 20.0]
Example 4: Sorting an array of numbers in descending order
To sort an array of numbers in descending order, you can either:
Tweak the comparison function from Example 3 and return -1 when num1 is greater than num2 and return 1 when num1 is lesser than num2 OR
Sort the array in ascending order first and then reverse it.
The code below implements the first approach. You can also use the compareNumbers
function from Example 3 and then use the reverse()
method after calling sort()
.
★ Important
Always specify a comparison function when sorting numbers to ensure expected sorting behavior.
function compareNumbersDesc(num1, num2) {
if(num1 > num2)
return -1;
if(num1 < num2)
return 1;
return 0;
}
function sortNumbersDesc() {
var numbers = [1,5,2,10,7,20,3];
Logger.log(numbers);
Logger.log(numbers.sort(compareNumbersDesc));
}
Output
[1.0, 5.0, 2.0, 10.0, 7.0, 20.0, 3.0]
[20.0, 10.0, 7.0, 5.0, 3.0, 2.0, 1.0]
Example 5: Sorting an array of strings in descending order
The easiest way to sort an array of strings in descending order is to first sort it in ascending order and then reverse it.
var colors = ["red", "blue", "green", "black", "orange", "purple"];
colors.sort().reverse();
Logger.log(colors);
Output
[red, purple, orange, green, blue, black]
Example 6: In the case of two-dimensional arrays, the sort() method will only apply one level deep. It will not sort the contents of the inner arrays
The array twoDArray
has two inner arrays: [5,1,4]
and [2,1,3]
. The sort method will not sort these inner arrays.
var twoDArray = [[5,1,4],[2,1,3]];
Logger.log(twoDArray);
Logger.log(twoDArray.sort());
Output
[[5.0, 1.0, 4.0], [2.0, 1.0, 3.0]]
[[2.0, 1.0, 3.0], [5.0, 1.0, 4.0]]
Example 7: When sorting an array of objects, use a comparison function to specify the desired sorting order
Consider the following array of objects:
var arr = [
{
id: 2,
name: "Jack"
},
{
id: 1,
name: "Paula"
}
];
Each of the objects in the array will result in the same value ([object
Object]
) when converted to a string. Therefore, sorting the array will not change the ordering at all unless you specify a comparison function. Here is an example of how to do that. Let's say we want to sort the above array based on the id
property of the objects.
function compareIds(a, b) {
if(a.id < b.id)
return -1;
if(a.id > b.id)
return 1;
return 0;
}
function sortObjects() {
var arr = [
{
id: 2,
name: "Jack"
},
{
id: 1,
name: "Paula"
}
];
Logger.log(JSON.stringify(arr));
//Default sort
arr.sort();
Logger.log(JSON.stringify(arr));
//Sort using the compareIds function
arr.sort(compareIds);
Logger.log(JSON.stringify(arr));
}
Output
[{"id":2,"name":"Jack"},{"id":1,"name":"Paula"}]
[{"id":2,"name":"Jack"},{"id":1,"name":"Paula"}]
[{"id":1,"name":"Paula"},{"id":2,"name":"Jack"}]
Example 8: To sort an array of dates, use a comparison function to specify the desired sorting behavior
The array arr
contains a number of date values. The compareDates function is used to sort the array in ascending order.
function compareDates(date1, date2) {
if(date1 > date2)
return 1;
if(date1 < date2)
return -1;
return 0;
}
function sortDates() {
var arr = [
new Date(2020,5,1),
new Date(2020,1,1),
new Date(2020,0,1)
];
Logger.log(arr);
arr.sort(compareDates);
Logger.log(arr);
}
Output
[Mon Jun 01 00:00:00 GMT-07:00 2020, Sat Feb 01 00:00:00 GMT-08:00 2020, Wed Jan 01 00:00:00 GMT-08:00 2020]
[Wed Jan 01 00:00:00 GMT-08:00 2020, Sat Feb 01 00:00:00 GMT-08:00 2020, Mon Jun 01 00:00:00 GMT-07:00 2020]
Conclusion
In this tutorial, you learned how to use the sort()
method of an array to sort its contents. Please remember that the sort()
method sorts the array in place. Also, it does not return a new array. Instead, it returns a reference to the array that was sorted.
You also learned how to use a comparison function to explicitly specify your desired sorting behavior.