Working with arrays
This article gives a systematic overview of how to work with arrays in Office Scripts.
Defining arrays
Section titled “Defining arrays”Define an empty array
Section titled “Define an empty array”To define an empty array with no elements, specify just [] as the value.
The type can’t be inferred from an empty array (there’s no way to tell what kind of data it will hold), so you also need to define the type at the same time. Office Scripts don’t allow the implicit any type, so leaving out the type may cause an error.
/** Empty array */const array: string[] = [];Define an array with initial values
Section titled “Define an array with initial values”To set initial values when you define an array, list the elements inside [], separated by commas.
The type is inferred from the initial values, so you can omit the type definition (the sample specifies the type explicitly).
/** Array with initial values */const fruits: string[] = ['Apple', 'Orange'];
/** Array with multiple data types */const mixed: (string | number)[] = [1200, 'Banana'];Add elements to an array
Section titled “Add elements to an array”You can use the Array.push method to add data to the end of an array.
const sports: string[] = [];
// Add an elementsports.push('Baseball');
// Add multiple elements at oncesports.push('Soccer', 'Basketball');Combine arrays
Section titled “Combine arrays”Here’s how to combine multiple arrays into a single array.
There are several ways to do this, and every method in the sample code gives the same result (['Apple', 'Orange', 'Banana']).
const array1 = ['Apple'];const array2 = ['Orange', 'Banana'];
// Combined arraysconst joined1 = [...array1, ...array2];const joined2 = array1.concat(array2);const joined3 = [array1, array2].flat();Get elements from an array
Section titled “Get elements from an array”Get an element by index
Section titled “Get an element by index”You can get the nth element of an array by specifying its index.
Indexes start at 0, so to get the second element, for example, specify 1 as the index.
const array = ['Apple', 'Orange', 'Banana'];
array[1]; // OrangeGet elements with destructuring assignment
Section titled “Get elements with destructuring assignment”With destructuring assignment, you can assign the elements of an array to multiple variables at once, in order from the beginning.
const array = ['Apple', 'Orange', 'Banana'];
const [apple, orange, banana] = array; // apple: Apple, orange: Orange, banana: Banana