Skip to content

Arrangement operation

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

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

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

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

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();

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

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;