forked from denoland/deno_std
-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_by.ts
44 lines (41 loc) · 1.17 KB
/
group_by.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
* Applies the given selector to each element in the given array, returning a
* Record containing the results as keys and all values that produced that key
* as values.
*
* @example
* ```ts
* import { groupBy } from "https://deno.land/std@$STD_VERSION/collections/group_by.ts";
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/assert/assert_equals.ts";
*
* const people = [
* { name: "Anna" },
* { name: "Arnold" },
* { name: "Kim" },
* ];
* const peopleByFirstLetter = groupBy(people, (it) => it.name.charAt(0));
*
* assertEquals(
* peopleByFirstLetter,
* {
* "A": [{ name: "Anna" }, { name: "Arnold" }],
* "K": [{ name: "Kim" }],
* },
* );
* ```
*/
export function groupBy<T, K extends PropertyKey>(
iterable: Iterable<T>,
selector: (element: T, index: number) => K,
): Partial<Record<K, T[]>> {
const ret: Partial<Record<K, T[]>> = {};
let i = 0;
for (const element of iterable) {
const key = selector(element, i++);
const arr: T[] = ret[key] ??= [];
arr.push(element);
}
return ret;
}