Splice() Function

In Google Apps Script, the splice() method is an array method that allows you to add or remove elements from an array. It modifies the original array in place, and returns the removed elements as a new array.

The splice() method takes two or three arguments. The first argument specifies the index at which to start adding or removing elements. The second argument specifies the number of elements to remove. If this argument is set to 0, no elements will be removed, and only new elements will be added. The third argument, which is optional, specifies the new elements to be added to the array.

Here is an example of using the splice() method to remove and add elements to an array of country names:

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

// Remove the second and third elements from the countries array
var removedCountries = countries.splice(1, 2);

// Add new elements to the countries array starting at index 1
countries.splice(1, 0, "Peru", "Chile");

// Output the modified array and the removed elements
Logger.log(countries); // Outputs: ["USA", "Peru", "Chile", "Brazil", "Argentina"]
Logger.log(removedCountries); // Outputs: ["Canada", "Mexico"]

In this example, we call the splice() method on the countries array to remove the second and third elements, "Canada" and "Mexico", from the array. The removed elements are assigned to a variable called removedCountries. Then, we call the splice() method again to add two new elements, "Peru" and "Chile", to the array starting at index 1. The original countries the array is modified in place, and the modified array and the removed elements are outputted to the log using the Logger.log() method.

You can also use the splice() method to remove and return a single element from an array:

var numbers = [1, 2, 3, 4, 5];

// Remove and return the third element from the numbers array
var removedNumber = numbers.splice(2, 1);

// Output the modified array and the removed element
Logger.log(numbers); // Outputs: [1, 2, 4, 5]
Logger.log(removedNumber); // Outputs: [3]

In this example, we call the splice() method on the numbers array to remove and return the third element, 3, from the array. The removed element is assigned to a variable called removedNumber. The original numbers the array is modified in place, and the modified array and the removed element are outputted to the log using the Logger.log() method.