I have a simple map script that takes an array and returns the nth column. Here is an example with n=2:
var array1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var newArray = array1.map(function(column){
return [column[2]]
});
Logger.log(newArray);
I want to make this into a function where the User inputs an array var data
and column number var n
and gets back the nth column. Here is how I've written the function:
function selectCol(data,n){
return data.map(function(column){
return [column[n]]
})
}
When I attempt to use this function, for example:
var array1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
Logger.log(selectCol(array1,2));
I get the error: TypeError: Cannot read property 'map' of undefined
.
How do I incorporate .map
into an actual function?
Per Robin's answer below, it appears I want to declare a dummy function at the beginning of the script and then select it as my main function:
CodePudding user response:
In Google Apps Script you always select a function that is being run.
What then happens is that the entire script is being run and then the function is called with no arguments.
If you run your code you will notice that the output is probably logged and then the error appears out of nowhere.
That is because the main code is executed as part of the setup, the error is happening because selectCol
is then called without arguments.
The solution is to have some main
function that can be run without arguments.