Drill

ProblemsTypeScript › data

How many of each

easydataTypeScript

A survey tallies how often each answer was given.

groupSizes(values: list<string>) → map<string, int>

Solve it in the editor →

Where you start

function groupSizes(values: string[]): Record<string, number> {
  
}

Worked examples

CallResult
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 TypeScript
function groupSizes(values: string[]): Record<string, number> {
  const result = new Map<string, number>();
  for (const v of values) {
    if (result.has(v)) result.set(v, result.get(v)! + 1);
    else result.set(v, 1);
  }
  return result;
}

The same problem in another language

More data problems in TypeScript