I was trying to run below Javascript code in Google Apps Script. But I was getting a syntax error in 3rd line.
Input: Array
ex: var array = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
Output: Object similar to Python Counter { "a": 5, "b": 3, "c": 2 }
function Counter(array) { //function returns a counter of the input array.
var count = {};
array.forEach(val => count[val] = (count[val] || 0) + 1);
return count;
}
My original question was to seek a help me to identify the error. The error of the above function is the arrow function which was identified by two users(@theMaster and @tehhowch). Then I created the below function which works in JavaScript but getting an error in Google Apps Script.
TypeError: Cannot call method "forEach" of undefined. (line 182, file "Code")
function createCounter(array) { //function returns a counter of the input array.
var countv = {};
array.forEach( function(val)
{countv[val] = (countv[val] || 0) + 1;
});
return countv;
};
var list = [40, 40, 10, 60, 60, 60, 60, 30, 30, 10, 10, 10, 10, 10, 40, 20]
Logger.log(createCounter(list));
Expected output: { "10": 6, "20": 1, "30": 2, "40": 3, "60": 4 }
I appreciate someone can help me with this.
=>
is not supported. Use regular function syntax. – TheMasterCounter
– tehhowchfunction createCounter(array) { //function returns a counter of the input array. var countv = {}; array.forEach( function(val) {countv[val] = (countv[val] || 0) + 1; }); return countv; } var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']; Logger.log(createCounter(list));
– xcen