michaelpri michaelpri - 22 days ago 6
Javascript Question

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

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

Answer

You can use Lo-Dash's countBy function:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
console.log(_.countBy(list));

JSFiddle example