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

  1. Summary
  2. Code
  3. Code Explanation
  4. Example
  5. AI Prompt


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 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.


Let’s say we have an array of prices for a set of products:

If we want to apply a 10% discount to each price, we can use the map() method:

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.

Similar Posts