groupBy.mjs 375 B

12345678910111213141516171819
  1. /**
  2. * Groups array items into a Map, given a function to produce grouping key.
  3. */
  4. export function groupBy(list, keyFn) {
  5. const result = new Map();
  6. for (const item of list) {
  7. const key = keyFn(item);
  8. const group = result.get(key);
  9. if (group === undefined) {
  10. result.set(key, [item]);
  11. } else {
  12. group.push(item);
  13. }
  14. }
  15. return result;
  16. }