Skip to content

Commit

Permalink
Create groupAndSum
Browse files Browse the repository at this point in the history
  • Loading branch information
pacmano1 authored Nov 18, 2022
1 parent 4b7aeae commit 2c95514
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions groupAndSum
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Author Tony Germano
// Discusion orginated on Mirth Slack from discussion started by nafwa03

function groupAndSum(arr, groupByKeys, sumKeys) {
const toGroupKey = o => groupByKeys.map(k => o[k]).join('|')
const newResultObject = sourceObj => groupByKeys
.map(k => [k, sourceObj[k]])
.concat(sumKeys.map(k => [k, 0]))
.reduce((targetObj, [k, v]) => (targetObj[k] = v, targetObj), {})
const groupMap = Object.create(null)
return arr.reduce((result, currentObject) => {
const key = toGroupKey(currentObject)
const pushSetAndGet = o => (result.push(o), groupMap[key] = o)
const resultObject = groupMap[key] || pushSetAndGet(newResultObject(currentObject))
sumKeys.forEach(k => { resultObject[k] += currentObject[k] || 0 })
return result
}, [])
}

0 comments on commit 2c95514

Please sign in to comment.