Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Javascript function similar to the Python Counter function?

Tags:

I am attempting to change a program of mine from Python to Javascript and I was wondering if there was a JS function like the Counter function from the collections module in Python.

Syntax for Counter

from collection import Counter list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'] counter = Counter(list) print counter 

output

Counter({'a':5, 'b':3, 'c':2}) 
like image 449
michaelpri Avatar asked Oct 11 '14 23:10

michaelpri


People also ask

What is counter in JavaScript?

The count() method counts the number of times console.

Is there a counter function in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.

Does JavaScript have range function like Python?

Is there a function in JavaScript similar to Python's range()? As answered before: no, there's not.


1 Answers

DIY JavaScript solution:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];  function Counter(array) {   var count = {};   array.forEach(val => count[val] = (count[val] || 0) + 1);   return count; }  console.log(Counter(list)); 

JSFiddle example

Update:

Alternative that uses a constructor function:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];  function Counter(array) {   array.forEach(val => this[val] = (this[val] || 0) + 1); }  console.log(new Counter(list)); 

JSFiddle example

like image 125
nitsas Avatar answered Oct 14 '22 11:10

nitsas