Home > front end >  Add Value to Itself in ForEach Using Keys Javascript
Add Value to Itself in ForEach Using Keys Javascript

Time:02-05

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}]

CodePudding user response:

You can use array.reduce to scan your array and group data by specified key:

let awards = [{Department:"AL",Money:100},{Department:"AL",Money:100}, 
{Department:"OB",Money:200},{Department:"AL",Money:100},{Department:"OB",Money:200}];

let aggregated = awards.reduce((acc,cur) => {
    let prev = acc.find(x => Object.keys(x)[0] === cur.Department);
    if(!prev) {
       acc.push({[cur.Department]:cur.Money});
    } else {
       prev[cur.Department]  = cur.Money;
    }
    return acc;
}, []);

console.log(aggregated);

Following this approach you don't modify existing array but create a new one with aggregated values.

CodePudding user response:

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 ??.

  •  Tags:  
  • Related