Last active
January 9, 2026 03:18
-
-
Save jonathanconway/297e29b68fc5d4f0b8469c79b9cd33ff to your computer and use it in GitHub Desktop.
Merges multiple maps of T to Array of U into one map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type MapOfArrays< | |
| TKey extends string | number | symbol, | |
| TArrayItem, | |
| TArray extends RelativeIndexable<TArrayItem>, | |
| > = Partial<Record<TKey, TArray>>; | |
| type ReadonlyMapOfArrays< | |
| TKey extends string | number | symbol, | |
| TArrayItem, | |
| > = MapOfArrays<TKey, TArrayItem, ReadonlyArray<TArrayItem>>; | |
| export function deepMergeMapsOfArrays< | |
| TKey extends string | number | symbol, | |
| TArrayItem, | |
| >( | |
| objects: readonly ReadonlyMapOfArrays<TKey, TArrayItem>[], | |
| ): ReadonlyMapOfArrays<TKey, TArrayItem> { | |
| const merged: MapOfArrays<TKey, TArrayItem, Array<TArrayItem>> = {}; | |
| const objectsEntriesFlat = objects | |
| .map((object) => Object.entries(object)) | |
| .flat() as [TKey, readonly TArrayItem[]][]; | |
| for (const [field, values] of objectsEntriesFlat) { | |
| merged[field] = merged[field] ?? []; | |
| merged[field].push(...values); | |
| } | |
| return merged as ReadonlyMapOfArrays<TKey, TArrayItem>; | |
| } | |
| // const a = { foo: [1, 2], bar: [3], baz: [] }; | |
| // const b = { foo: [4, 5, 6], bar: [7, 8], baz: [9] }; | |
| // deepMergeMapsOfArrays([a, b]); | |
| // Output: | |
| // { | |
| // foo: [ 1, 2, 4, 5, 6 ], | |
| // bar: [ 3, 7, 8 ], | |
| // baz: [ 9 ] | |
| // } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment