Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active April 8, 2021 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsuby/8d6c8a124cdbe9f257f30ea9dfb2141b to your computer and use it in GitHub Desktop.
Save matsuby/8d6c8a124cdbe9f257f30ea9dfb2141b to your computer and use it in GitHub Desktop.
オブジェクトの和
/**
* 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