Skip to content

Instantly share code, notes, and snippets.

@dcorns
Created May 17, 2017 01:24
Show Gist options
  • Save dcorns/8ccf0072b5b4c953a02070f9c942bbee to your computer and use it in GitHub Desktop.
Save dcorns/8ccf0072b5b4c953a02070f9c942bbee to your computer and use it in GitHub Desktop.
sum the values of a given array of objects sorted by a given property to sort on and the property containing the values to sum
/**
* combine-sets
* Created by dcorns on 5/16/17
* Copyright © 2017 Dale Corns
* MIT Licensed
*/
'use strict';
const data = [
{
"paid_savings": 8841.88,
"queue_week": "201714",
},
{
"paid_savings": 14021.05,
"queue_week": "201714",
},
{
"paid_savings": 17708.20,
"queue_week": "201715",
},
{
"paid_savings": 10270.08,
"queue_week": "201715",
},
{
"paid_savings": 4405.66,
"queue_week": "201714",
}
];
const combinedSums = (ary, combineKey, valueKey) => {
let visited = [];
let testIdx = 0;
let result = [];
ary.forEach((item) => {
testIdx = visited.indexOf(item[combineKey]);
if(testIdx < 0) {
visited.push(item[combineKey]);
result.push(item);
}
else{
result[testIdx][valueKey] += item[valueKey];
}
});
return new Promise ((resolve, reject) => {
resolve (result);
});
};
combinedSums(data, 'queue_week', 'paid_savings').then((res) => {
console.log(res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment