The Array method map() in Apps Script

The Array method map() returns a new array that is populated with values obtained by calling a function on every element of the original array.

Given the array [1,2,3] and a function f(x), the map method will apply the function to each element in the array and will return the array [f(1), f(2), f(3)].

Syntax

array.map(callbackFunction)

Parameters

callbackFunction (required):

  • This function will be executed once for every element in the array and a new array containing the output of these executions will be returned.

The callbackFunction can accept three arguments:

  • value (required): The current value being processed.

  • index (optional): The index of the value in the array.

  • array (optional): The original array that the map() method was called on.

Return value

The map() method returns a new array containing values obtained by executing the callbackFunction on every element of the original array.

How does the map() Array method work?

The map() method will execute the callbackFunction once for every element in the array. The value returned by the callbackFunction will be added to a new array. This new array will then be returned.

Consider an input array named arr containing 5 values and a callback function named f().

Input array

val1

val2

val3

val4

val5

Output array

The value returned by arr.map(f) is an array whose elements are obtained by executing the function f() on each value of arr.

f(val1)

f(val2)

f(val3)

f(val4)

f(val5)

Examples

Example 1: Using the map() Array method to square values in an array

Example 1.1

In the code below, the function square(value) is the callbackFunction parameter in the map() method. This function is executed once for every element in the array values and it returns the square of each element. The array squaredValues contains these values.

function mapEx1_1() {
  var values = [1,2,3,4,5];
  var squaredValues = values.map(square);
  Logger.log(squaredValues);
}

function square(value) {
  return value * value;
}

Output

[1.0, 4.0, 9.0, 16.0, 25.0]

Example 1.2

Instead of defining the function square() separately and then passing it as a parameter, you can also define it in-line. The code below shows you how to do this.

function mapEx1_2() {
 var values = [1,2,3,4,5];
 var squaredValues = values.map(function(value) {
   return value * value;
 });
 Logger.log(squaredValues);
}

Output

[1.0, 4.0, 9.0, 16.0, 25.0]

Conclusion

In this tutorial, you learned how to use the map() Array method to create a new array that is obtained by applying a function to every element of the original array.

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.