Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

Python Counter equivalent in javascript

✨ python [object Object]

from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter
// Counter({'a':5, 'b':3, 'c':2})

✨ Algorithm

  • Caution: Javascript key becomes string, not number.
const counter = (array) => {
  const freq = {};
  for (const value of array) {
    freq[value] = (freq[value] || 0) + 1;
  }
  return freq;
};
const nums = ["a", "b", "c", "b", "a", "b", "c", "a", "a", "a"];
const obj = counter(nums);
console.log(obj); // {a: 5, b: 3, c: 2}