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})
The count() method counts the number of times console.
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.
Is there a function in JavaScript similar to Python's range()? As answered before: no, there's not.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With