Skip to main content

Arrangement operation

Here, we will explain the systematic operation method of arrays in office scripts.

Comparison with VBA

VBA features a very strict type definition, and needs to be redefined to change the number of elements.

The Office Scripts has no limit on the number of elements of the array unless complex type definitions are implemented.

Definition of array

Define the empty array

If you define an empty array that does not have an element, specify only [] as a value.

When defining an empty array, the type inference does not work (do not know what data to store), so it is necessary to define the type at the same time.

/** empty array */
const array: string[] = [];

Define an array with the initial value

If you set the initial value at the same time as the array definition, specify the element in the [] in a comma separation.

Since type inference works, type definitions can be omitted.

/** Arrangement with initial values */
const fruits: string[] = ['Apple', 'Orange'];

/** Arrangement with multiple data types */
const mixed: (string | number)[] = [1200, 'Banana'];

Add elements to array

You can add data to the array using the Array.push method.

const sports: string[] = [];

// Add element
array.push('baseball');

// Add multiple elements at the same time
array.push('Football', 'basketball');

Bond the array

This is a description method when multiple arrays want to be a single array.

Many methods are provided as standard, and the same result is used using any method of sample code.

const array1 = ['Apple'];
const array2 = ['Orange', 'banana'];

// Combined array
const joined1 = [...array1, ...array2];
const joined2 = array1.concat(array2);
const joined3 = [array1, array2].flat();

Acquire elements from array

Acquire by specifying the index

You can obtain the N's N's element of the array.

Since the index starts from 0, for example, if you want to get the second element, specify 1 in the index.

const array = ['Apple', 'Orange', 'Banana'];

array[1]; // Orange

Acquired using split assignment

By using split assignment, which is a variable definition method, you can operate the array data.

const array = ['Apple', 'Orange', 'Banana'];

const [apple, orange, banana] = array;