Applying map method to Array in Apps Script
This post is a corrected post after AI explains the code included in the book “Google Apps Script 101: Building Work Automation For Free”. Added a strikethrough when editing what AI has written, and added color when edited by author
Table of Contents
Summary
In this blog post, we will explore how to use the map()
method in Apps Script to perform array mapping. We will learn how to apply a specified function to each element of an array and create a new array with the results.
Code
1 2 3 4 5 |
function multiply2() { const data = [1, 2, 3, 4, 5] let dataMap = data.map(item => item * 2) Logger.log(dataMap) } |
Code Explanation
The code defines a function named multiply2
. Inside the function, an array data
is declared and initialized with five numbers.
The map()
method is then used on the data
array, applying an arrow function to each element. The arrow function multiplies each element by 2. The resulting mapped array is stored in the dataMap
variable.
map() is similar to filter(), but the difference is that instead of entering filtering conditions for elements, you enter a function to apply to the elements. item => item * 2 takes the item, doubles it, and replaces it in the item’s place.
Finally, the mapped array is logged using the Logger.log()
method.
Example
Let’s say we have an array of prices for a set of products:
1 |
const prices = [10, 20, 30, 40, 50] |
If we want to apply a 10% discount to each price, we can use the map()
method:
1 |
const discountedPrices = prices.map(price => price * 0.9) |
The discountedPrices
array will now contain the updated prices after the discount has been applied.
AI Prompt
Write a function that multiplies each element of an array by 2 using the map()
method. Log the resulting array.