I'm trying to loop thru an array and sum values for each Department in the array. See below. I'm trying to loop thru the objects and add all of the Money values (sum them) per Department.
var awards = [
{ Department: "AL", Money: 100 },
{ Department: "AL", Money: 100 },
{ Department: "OB", Money: 200 },
{ Department: "AL", Money: 100 },
{ Department: "OB", Money: 200 }
];
var myObj = {},
array1 = [],
sum = 0,
array2 = [],
myObj2 = {};
var activeDepartments = ["AL", "OB"];
//FOREACH
Object.keys(awards).forEach(function(key, index) {
var department = awards[key].Department;
var money = awards[key].Money;
sum = 0;
// console.log(this[index].Money);
if (activeDepartments.indexOf(department) !== -1) {
sum += this[index].Money;
myObj[department] = sum;
}
//console.log(index);
}, awards);
array1.push(myObj); //PUSH OBJECT TO ARRAY
console.log(array1);
//trying to get object to look like this: [{AL:300}, {OB:400}]
Instead of sum = 0, you need sum = myObj[department] ?? 0;. This way, you don't resend the sum each iteration of the loop. What that line of code does is check if the expression to the left of ?? (myObj[department]) is defined. If it is, it assigns its value to sum. Otherwise, it assigns the value of the expression to the right of ??.
Similiar question has been already resolved in Sum similar keys in an array of objects
in your case the code would look like this
var awards = [
{ Department: "AL", Money: 100 },
{ Department: "AL", Money: 100 },
{ Department: "OB", Money: 200 },
{ Department: "AL", Money: 100 },
{ Department: "OB", Money: 200 }
];
var holder = {};
awards.forEach(function(award) {
if (holder.hasOwnProperty(award.Department)) {
holder[award.Department] = holder[award.Department] + award.Money;
} else {
holder[award.Department] = award.Money;
}
});
var finalArray = [];
for (var prop in holder) {
finalArray.push( {[prop]: holder[prop]} );
}
console.log(finalArray);