Group By And Count By Reduce

Group array items by a key function and count occurrences for aggregation summaries and frequency analysis.

JavascriptData Integrity

Code

javascriptsnippet
1 line
export function groupBy(items,keyFn){return items.reduce((acc,item)=>{const key=keyFn(item);(acc[key]??=[]).push(item);return acc;},{});}export function countBy(items,keyFn){return items.reduce((acc,item)=>{const key=keyFn(item);acc[key]=(acc[key]??0)+1;return acc;},{});}export function uniqueBy(items,keyFn){const seen=new Map();for(const item of items){const key=keyFn(item);if(!seen.has(key))seen.set(key,item);}return[...seen.values()];}

How the snippet works

Count the functions groupBy, countBy and uniqueBy as the entire surface area of Group By And Count By Reduce.

Applying it

Entry signature: export function groupBy(items,keyFn)

groupBy is the public entry point; everything else in the file exists to support it.

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `groupBy`, `countBy`, `uniqueBy` at load time.