Shift() Function

In Google Apps Script, the shift() method is an array method that allows you to remove the first element from an array. It modifies the original array in place, and returns the removed element.

Here is an example of using the shift() method to remove the first element from an array of country names:

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

// Remove the first element from the countries array
var removedCountry = countries.shift();

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

In this example, we call the shift() method on the countries array to remove the first element, "USA", from the array. The original countries array is modified in place, and the removed element is assigned to a variable called removedCountry. The modified countries array and the removed element are outputted to the log using the Logger.log() method.

You can also use the shift() method to remove and return the first element from an array of objects:

var persons = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 40 }
];

// Remove and return the first person from the persons array
var removedPerson = persons.shift();

// Output the modified array and the removed element
Logger.log(persons); // Outputs: [{ name: "Jane", age: 25 }, { name: "Bob", age: 40 }]
Logger.log(removedPerson); // Outputs: { name: "John", age: 30 }

In this example, we call the shift() method on the persons array to remove and return the first object, { name: "John", age: 30 }, from the array. The original persons array is modified in place, and the removed object is assigned to a variable called removedPerson. The modified persons array and the removed object are outputted to the log using the Logger.log() method.

In conclusion, the shift() method in Google Apps Script is a useful tool for removing the first element from an array. It can be used in various contexts to modify and transform array data, such as removing the first value or object from an existing array.