Home > Blockchain >  Summing up values for a specific key in Javascript
Summing up values for a specific key in Javascript

Time:10-09

I see the object on the below screenshot when i do console.log(changes)

{
    "dt": "2022-07-01T00:00:00.000Z",
    "gradeName": "grade 3",
    "effectiveFrom": "2022-07-01T00:00:00.000Z",
    "salary": "10000.0000",
    "salaryEffective": "2022-07-01T00:00:00.000Z",
    "leaveDate": "2022-07-10T00:00:00.000Z",
    "dailyRate": "328.77"
}
{
    "dt": "2022-07-02T00:00:00.000Z",
    "gradeName": "grade 3",
    "effectiveFrom": "2022-07-01T00:00:00.000Z",
    "salary": "10000.0000",
    "salaryEffective": "2022-07-01T00:00:00.000Z",
    "leaveDate": "2022-07-10T00:00:00.000Z",
    "dailyRate": "328.77"
}

What would be the right way to sum up salary values for a specific grade ? I am stuck on trying to figure out how to loop over the object in the first place. I tried,

for (const [index, [key, value]] of Object.entries(Object.entries(changes))) {
        console.log(`${index}: ${key} = ${value}`);
      }
  

where changes refers to the object.

I am seeing the below output in the console,

enter image description here

CodePudding user response:

function sumBy(grade) {
  let sumSoFar = 0;
  for (const {gradeName, salary} of changes)
    if (gradeName === grade)
      sumSoFar  = Number(salary);

  return sumSoFar;
}

CodePudding user response:

You can make use of reduce to calculate the sum of all the salary values. Below is a example.

const dummyArr = new Array(5).fill(5).map((val, ind) => ({
  salary: ind   1
}));
console.log(dummyArr);

console.log(dummyArr.reduce((prev, curr) => prev   parseFloat(curr.salary), 0));

  • Related