The Array method unshift() in Apps Script
The Array method
unshift() adds one or more elements to the beginning of an array and returns its new size.
This tutorial assumes that you're familiar with:
Basic Apps Script concepts (such as Arrays in Apps Script).
How to create and run simple Apps Script scripts using the script editor in Google Sheets.
array.unshift(val, val2, …, val3)
One or more values to be added to the beginning of the array.
The length of the array after adding elements to it.
The code below uses the
unshift() array method to add elements to the beginning of the array
In Apps Script, you can only run functions. So you have to copy and paste the code snippet below into a function before you run it.
var colors = ["red", "blue"]; Logger.log(colors); Logger.log(colors.length); // Adding just one element var length = colors.unshift('purple'); Logger.log(colors); Logger.log(length); // Adding two elements length = colors.unshift('green', 'yellow'); Logger.log(colors); Logger.log(length);
[purple, red, blue]
[green, yellow, purple, red, blue]
In this tutorial, you learned how to use the
unshift() array method to add elements to the beginning of an array.
Stay up to date
I'd appreciate any feedback you can give me regarding this post.
Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!