Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Last active January 9, 2026 03:18
Show Gist options
  • Select an option

  • Save jonathanconway/297e29b68fc5d4f0b8469c79b9cd33ff to your computer and use it in GitHub Desktop.

Select an option

Save jonathanconway/297e29b68fc5d4f0b8469c79b9cd33ff to your computer and use it in GitHub Desktop.
Merges multiple maps of T to Array of U into one map
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