1
votes

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.

1
Arrow syntax => is not supported. Use regular function syntax.TheMaster
@tehhowch Now I am getting an error. "TypeError: Cannot call method "forEach" of undefined." function Counter(array) { //function returns a counter of the input array. var count = {}; array.forEach( function(val) {count[val] = (count[val] || 0) + 1; }); return count; }xcen
Your problem is in your code that calls Countertehhowch
@tehhowch I get the same error after changing the function name. "TypeError: Cannot call method "forEach" of undefined. (line 183, 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 = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']; Logger.log(createCounter(list));xcen

1 Answers

1
votes

I tried it and I get: {60=4.0, 40=3.0, 30=2.0, 20=1.0, 10=6.0}

function testCounter(){
  var s=createCounter([40, 40, 10, 60, 60, 60, 60, 30, 30, 10, 10, 10, 10, 10, 40, 20]);
  Logger.log(s);
}

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;
}