β¨ 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);