Arrays in Apps Script

Arrays are a fundamental data structure in computer programming that allows you to store and manipulate collections of values. Google Apps Script, a scripting language used to automate tasks and build applications in the Google Workspace ecosystem, provides a robust set of tools for working with arrays.

Creating an Array

To create an array in Google Apps Script, you can use the following syntax:

// create an empty array
var myArray = [];

// create an array with initial values
var myOtherArray = [1, 2, 3, 4, 5];

In Google Apps Script, arrays have an indexing system that starts at 0 and not 1. For instance, if we have an array of country names where the first country is at index 0, the second country will be at index 1. Since the indexing system starts at 0, the last country in the array will have the index N – 1, where N is the number of countries.

Let’s take an example to understand better how arrays work in Google Apps Script. Suppose we want to create an array of country names, and we want to access the third country in the array:

var countries = ["USA", "Canada", "Mexico", "Brazil", "Argentina"];
var thirdCountry = countries[2];

Arrays to store tabular data

Suppose you are building a script to store and manipulate data about books in a library. Each book has multiple attributes, such as title, author, and publication date. You can store this data in a grid-like structure with a two-dimensional array.

var library = [
  ["The Great Gatsby", "F. Scott Fitzgerald", 1925],
  ["To Kill a Mockingbird", "Harper Lee", 1960],
  ["1984", "George Orwell", 1949]
];

In this example, the library the variable is a two-dimensional array with three rows (representing three books) and three columns (representing the book’s title, author, and publication date). To access an element in the array, you use the square bracket notation with the row index and the column index:

// Get the author of "To Kill a Mockingbird"
var author = library[1][1]; // Returns "Harper Lee"

In this example, we access the element in the second row (index 1) and the second column (index 1) of the library array and assign the value to a variable called author. The value author will be “Harper Lee”.