← All Exercises

Aggregate a CSV Stream by Group

basicjavascript~20min

Background

Pipeline code is usually a group-by over a stream. Doing it with explicit parsing exposes bad rows instead of hiding them behind a library.

Problem

Parse CSV text with a header row, sum a numeric column per group, and return sorted group totals.

Input

JSON object: { csv: string, groupBy: string, sumField: string }

Output

JSON array of { group, total } sorted by group

Sample tests

Sample 1

Input: {"csv":"team,amount\ncore,10\nweb,5\ncore,15\n","groupBy":"team","sumField":"amount"}
Expected: [{"group":"core","total":25},{"group":"web","total":5}]

Sample 2

Input: {"csv":"region,count\nus,3\n","groupBy":"region","sumField":"count"}
Expected: [{"group":"us","total":3}]

Your solution

Learning objective

Write a group-by that fails loudly on malformed input.