xcen
xcen

Reputation: 692

Google apps script Counter function

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.

Upvotes: 1

Views: 1021

Answers (1)

Cooper
Cooper

Reputation: 64042

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

Upvotes: 1

Related Questions