map() Function

In Google Apps Script, the map() method is an array method that creates a new array with the results of calling a provided function on every element in the array. The method takes a callback function as an argument, which is called for each element in the array. The callback function should return the new value for the element.

Here is an example of using the map() method to create a new array with the lengths of each country name in an array:

var countries = ["USA", "Canada", "Mexico", "Brazil", "Argentina"];

// Create a new array with the lengths of each country name
var lengths = countries.map(function(country) {
  return country.length;
});

// Output the new array
Logger.log(lengths); // Outputs: [3, 6, 6, 6, 9]

In this example, we call the map() method on the countries array and pass a callback function that returns the length of each country name. The method iterates over each element in the array and calls the callback function for each element, passing the value of the element as an argument. The callback function returns the length of the country name, which is used to create a new array with the same length as the original array. The new array is assigned to a variable called lengths, which is outputted to the log using the Logger.log() method.

You can also use the map() method to transform an array of objects into a new array with a selected property:

var persons = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 40 },
  { name: "Mary", age: 35 }
];

// Create a new array with only the names of each person
var names = persons.map(function(person) {
  return person.name;
});

// Output the new array
Logger.log(names); // Outputs: ["John", "Jane", "Bob", "Mary"]

In this example, we call the map() method on the persons array and pass a callback function that returns the name of each person. The method iterates over each element in the array and calls the callback function for each element, passing the value of the element as an argument. The callback function returns the name of the person, which is used to create a new array with the same length as the original array. The new array is assigned to a variable called names, which is outputted to the log using the Logger.log() method.