From 2af0bf5b9a30abf28db68c8c3e54c48c722e6c14 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Mon, 6 May 2024 12:29:23 -0300 Subject: sugar: groupArray --- src/util/sugar.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/util/sugar.js') diff --git a/src/util/sugar.js b/src/util/sugar.js index 1c057ed1..3fa3fb46 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -136,6 +136,23 @@ export function stitchArrays(keyToArray) { return results; } +// Like Map.groupBy! Collects the items of an unsorted array into buckets +// according to a per-item computed value. +export function groupArray(items, fn) { + const buckets = new Map(); + + for (const [index, item] of Array.prototype.entries.call(items)) { + const key = fn(item, index); + if (buckets.has(key)) { + buckets.get(key).push(item); + } else { + buckets.set(key, [item]); + } + } + + return buckets; +} + // Turns this: // // [ -- cgit 1.3.0-6-gf8a5