Skip to content

Instantly share code, notes, and snippets.

@matsuby

matsuby/sumObjects.ts

Last active Apr 8, 2021
Embed
What would you like to do?
オブジェクトの和
/**
* sumObjects([
* {a: 1, b: 2},
* {b: 3, c: 4},
* ])
* => {a: 1, b: 5, c: 4}
*/
const sumObjects = (
objects: Record<string, number>[]
): Record<string, number> =>
objects.reduce((acc, cur) => {
Object.entries(cur).forEach(([k, v]) => {
acc[k] = (acc[k] ?? 0) + v
})
return acc
}, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment