Menu

Quick data munging: group, sum and bucket a CSV
📰

Quick data munging: group, sum and bucket a CSV

DEV Community: typescript·JSLab·28 days ago
#lpWbT489
#devtotypescript#devto#dev#const#date
Long article (672 words) — no AI summary yet.
Reading 0:00
15s threshold

Someone sends you a CSV and a question: "totals by region? and by week?" It's not worth a notebook, a database or a project. It's worth twenty lines.

The data

const csv = `date,region,product,amount 2026-10-05,EU,Pro,120 2026-10-06,US,Basic,80 2026-10-06,EU,Basic,45.5 2026-10-12,APAC,Pro,210 2026-10-13,US,Pro,120` ;

Enter fullscreen mode

Exit fullscreen mode

Step 1: rows (the naive way)

const [ header , ... lines ] = csv . trim (). split ( " \n " ); const keys = header . split ( " , " );

const rows = lines . map (( line ) => { const cells = line . split ( " , " ); return Object . fromEntries ( keys . map (( k , i ) => [ k , cells [ i ]])); });

Enter fullscreen mode

Exit fullscreen mode

Fine for this file. Hold that thought.

Step 2: totals by region with Object.groupBy

Object.groupBy (ES2024) does the bucketing that used to need a reduce :

const byRegion = Object . groupBy ( rows , ( r ) => r . region );

const totals = Object . fromEntries ( Object . entries ( byRegion ).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.