Skip to content

Working with arrays

This article gives a systematic overview of how to work with arrays in Office Scripts.

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[] = [];

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'];

You can use the Array.push method to add data to the end of an array.

const sports: string[] = [];
// Add an element
sports.push('Baseball');
// Add multiple elements at once
sports.push('Soccer', 'Basketball');

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 arrays
const joined1 = [...array1, ...array2];
const joined2 = array1.concat(array2);
const joined3 = [array1, array2].flat();

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]; // Orange

Get 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