In our previous tutorial (Lesson #15), we covered how to neatly extract matching records using Array.filter().
In this 16th lesson, we will explore one of the most powerful and versatile methods in Google Apps Script (GAS) and JavaScript: Array.map(), which allows you to transform and process entire arrays in bulk!
When working with Google Sheets data in daily business operations, tasks like “recalculating all prices with a 10% sales tax,” “adding an honorific title to every customer name,” or “extracting specific columns and reshaping them into a 2D array to write back to the sheet” come up all the time.
While you can write standard for loops to handle elements one by one, mastering Array.map() will cut your code size by more than half, producing clean, readable, and bug-resistant programs.
To ensure beginners never get lost, we will walk through the concepts using visual conveyor-belt analogies and detailed line-by-line code explanations!
1. What Is Array.map() in the First Place?
In short, Array.map() is “a method that applies a specific transformation rule to every element in an array and automatically creates a new array with the results.”
Imagine a Magic Factory Conveyor Belt!
Visualizing map() as an automated factory conveyor belt makes it super intuitive to understand:
- Raw Material (Original Array):
[100, 200, 300]arrives riding on the conveyor belt. - Processing Machine (Logic inside map): Applies the operation “multiply by 1.1 (add tax)” to every item that passes through.
- Finished Goods (New Array): A brand-new array
[110, 220, 330]emerges from the other side.
The key point to remember is that “the original array is never modified; a completely new, transformed array is produced separately.”
Why Use map() Instead of a for Loop?
You might wonder, “Can’t we just iterate using a traditional for loop?” Let us compare both approaches side-by-side.
[Pattern A] Using a Traditional for Loop
var original = [100, 200, 300]; var result = []; // Prepare an empty array in advance for (var i = 0; i < original.length; i++) { var taxIncluded = Math.floor(original[i] * 1.1); result.push(taxIncluded); // Append items one by one }[Pattern B] Using map()
var original = [100, 200, 300]; var result = original.map(function(price) { return Math.floor(price * 1.1); });With a for loop, you need tedious boilerplate setup: declaring an empty array, managing a counter variable (i), writing boundary conditions, and calling push().
With map(), on the other hand, you only need to declare what processing logic to apply. Fewer boilerplate steps mean fewer typos and errors in your scripts!
2. Basic Syntax of Array.map()
Let us examine the foundational syntax of map().
var newArray = originalArray.map(function(item) { // Write transformation logic for each item here return transformedValue; });Breaking Down the Arguments
originalArray: The source array containing the data you want to transform.function(item): Each element of the array is passed one by one into this parameter. You can name the variable anything you like (e.g.,item,row,val).return: Returns the processed value. This returned value becomes the element in your new array.
*Note: In modern JavaScript (ES6+), you can write this even more concisely using arrow functions (=>).
// Arrow function syntax (functions identically) var newArray = originalArray.map(item => transformedValue);💡 Review Arrow Functions Here! For comprehensive rules and best practices on writing arrow functions (
=>), check out Lesson #15 on “Array.filter()”. Feel free to refer back if you want a quick refresher on arrow syntax!
3. STEP 1: Preparation! Create a “Sapporo Soup Curry Tour List”
Now let us run real code in a Google Sheet! For a taste of Hokkaido local culture, we will use a price list of famous Sapporo soup curry restaurants as our sample dataset.
Setting Up the Spreadsheet
- Open a new Google Spreadsheet.
- Rename the sheet tab to “Soup Curry List”.
- Enter the sample data as shown below:
| A | B | |
| 1 | Shop Name | Price Excl. Tax (JPY) |
| 2 | Soup Curry GARAKU | 1200 |
| 3 | Magic Spice | 1150 |
| 4 | RAMAI | 1100 |
- From the top menu, navigate to Extensions > Apps Script to open the script editor.
4. STEP 2: [Hands-On] Calculate Tax-Included Prices for a 1D Array in Bulk
Let us begin with the simplest use case: applying map() to a 1-dimensional array (a list of numbers).
Entering the Script
Clear any existing boilerplate code in the editor and paste the following function:
function convertToTaxIncluded() { // 1. Prepare soup curry prices excluding tax (1D array) var pricesExcludingTax = [1200, 1150, 1100]; // 2. Create a new array multiplying all values by 1.1 using map() var pricesIncludingTax = pricesExcludingTax.map(function(price) { // price receives 1200 -> 1150 -> 1100 sequentially var taxIn = Math.floor(price * 1.1); // Round down fractions with Math.floor return taxIn; // Return the value to be appended to the new array }); // 3. Compare original and transformed arrays in the log Logger.log("Original price excl. tax: " + pricesExcludingTax); Logger.log("Converted price incl. tax: " + pricesIncludingTax); }Execution Steps
- Click the Save disk icon at the top of the editor.
- Click the Run button.
- Check the Execution Log at the bottom of the window.
Execution Results
Info Original price excl. tax: 1200,1150,1100 Info Converted price incl. tax: 1320,1265,1210The tax calculation defined inside map() was sequentially applied to 1200, 1150, and 1100, generating a fresh array [1320, 1265, 1210] perfectly!
5. STEP 3: [The Core of GAS] 2D Arrays (getValues) × map() × setValues()
Now we arrive at the real superpower of Google Apps Script! In production GAS workflows, the single most common pipeline is: “Fetch a 2D array with Range.getValues(), transform it via map(), and write it back using Range.setValues().”
In GAS, spreadsheet tabular data is handled as a two-dimensional array (nested arrays where rows contain columns):
// Data retrieved via sheet.getRange("A2:B4").getValues() [ ["Soup Curry GARAKU", 1200], // Row 0 (Data for 1 row) ["Magic Spice", 1150], // Row 1 ["RAMAI", 1100] // Row 2 ]Let us write a script that calculates the tax-included price from this data and writes it into Column C in one single operation.
Practical Code
function updateTaxIncludedColumn() { // 1. Get the active spreadsheet and sheet var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getActiveSheet(); // 2. Fetch range A2:B4 (shop name & price excl. tax) as a 2D array var data = sheet.getRange("A2:B4").getValues(); // 3. Use map() to format a new 2D array ready to write into Column C var taxIncludedData = data.map(function(row) { // row contains a 1-row array (e.g., ["Soup Curry GARAKU", 1200]) var priceExcludingTax = row[1]; // Extract index 1 (Column B: price excl. tax) var priceIncludingTax = Math.floor(priceExcludingTax * 1.1); // Multiply by 1.1 // [CRITICAL] Wrap in [] to return a 2D array structure like [[val1], [val2], ...] for setValues! return [priceIncludingTax]; }); // 4. Batch write the newly created array to range C2:C4! sheet.getRange("C2:C4").setValues(taxIncludedData); Logger.log("Successfully wrote tax-included prices to column C in bulk!"); }💡 Why Must We Return Bracketed [priceIncludingTax]?
This is the single most critical point in GAS array manipulation! Range.setValues() strictly requires data in a 2D array format matching the grid dimensions (rows × columns).
If you return a naked scalar like return priceIncludingTax;, the result is a 1-dimensional array [1320, 1265, 1210]. When passed to setValues(), GAS throws a “The parameters do not match the signature” exception and halts execution.
By returning [priceIncludingTax] inside square brackets [ ], the output structure becomes [[1320], [1265], [1210]]—a “3 rows × 1 column” 2D array that fits cell range C2:C4 seamlessly!
6. 5 Common Pitfalls Beginners Face with map() and How to Fix Them
Whenever you wonder, “Why isn’t my script working?” or encounter sudden errors with map(), run through this 5-point checklist.
Trap 1: Forgetting the return Statement (Resulting in undefined)
This is the number one most frequent mistake! If you forget to write return inside your callback, every single element in your resulting array will become undefined.
- ✕ Mistake Example
var result = prices.map(function(price) { price * 1.1; // Missing return! }); // result becomes [undefined, undefined, undefined]- ◯ Solution: Always make sure you explicitly write
returnat the end of the callback body.
Trap 2: Assuming the Original Array Is Modified in Place
map() is a non-destructive method that constructs a new array; it does not alter the source array in place.
- ✕ Common Misunderstanding
var prices = [100, 200, 300]; prices.map(price => price * 1.1); // prices is still [100, 200, 300] here!- ◯ Solution: Always store the output in a new variable like
var newPrices = prices.map(...), or reassign it withprices = prices.map(...).
Trap 3: Dimension Mismatches When Passing Data to setValues()
As explained earlier, setValues() accepts only 2-dimensional arrays.
- Example Error Message:
Exception: The parameters (number[]) do not match the method signature for SpreadsheetApp.Range.setValues. - ◯ Solution: Verify that your return statement wraps values in square brackets, such as
return [transformedValue];.
Trap 4: Confusing Array.map() with Array.filter()
Because both filter() and map() are used extensively, developers frequently confuse their roles.
| Method | Purpose | Resulting Array Length |
Array.filter() | Extracts / narrows down elements matching conditions | Equal to or fewer elements than original |
Array.map() | Transforms / converts all elements using a formula | Exactly the same count as original |
Remember the simple rule of thumb: “Use filter() to reduce count, use map() to change format!”
Trap 5: Accidental Return Omissions with Arrow Functions
(For a deeper dive into arrow functions, feel free to refer to our guide in Lesson #15 on Array.filter()!)
When working with arrow functions, whether you include curly braces { } fundamentally changes how return behaves.
// ◯ OK: No curly braces => automatically returned var res1 = prices.map(price => price * 1.1); // ✕ NG: Braces included without return => results in undefined! var res2 = prices.map(price => { price * 1.1 }); // ◯ OK: If braces are used, return must be explicit var res3 = prices.map(price => { return price * 1.1; });When starting out, writing standard functions like function(item) { return ... } is the safest way to avoid accidental bugs!
7. Summary & What’s Coming Next
In this guide, we explored how to use Array.map() to transform array data in Google Apps Script cleanly and efficiently.
Key Takeaways for Today
Array.map()processes every item to build an entirely new array- Produces far cleaner and less error-prone code than traditional
forloops - Essential for transforming 2D arrays fetched with
getValues()before saving viasetValues() - When formatting for
setValues(), always enclose values likereturn [processedValue]
With both filter() and map() in your toolkit, you now have complete control over data filtering and transformation in GAS!
In Lesson #17, we will cover Sheet.insertRowBefore() to dynamically insert new rows at designated positions. This is an indispensable technique for audit logging and automated data entry, so stay tuned!
