Problems › JavaScript › data
How many of each
A survey tallies how often each answer was given.
- Count how many times each distinct string appears.
- Every distinct value that appears earns an entry in the result.
groupSizes(values: list<string>) → map<string, int>
Where you start
function groupSizes(values) {
}
Worked examples
| Call | Result |
|---|---|
groupSizes(["a","b","a"]) | {"a":2,"b":1} |
groupSizes(["x"]) | {"x":1} |
groupSizes(["p","p","p"]) | {"p":3} |
groupSizes(["a","b","c"]) | {"a":1,"b":1,"c":1} |
Hint
Add one to the map entry for each value you meet.
Reference solution in JavaScript
function groupSizes(values) {
const result = new Map();
for (const v of values) {
if (result.has(v)) result.set(v, result.get(v) + 1);
else result.set(v, 1);
}
return result;
}