Skip to content Skip to sidebar Skip to footer

How To Get A The Sum Of Multiple Arrays Within An Array Of Objects?

I was wondering how you get the sum of multiple arrays within an array of objects. My code is as follows: const employeeList = [ { 'name': 'Ahmed', 'scores': [

Solution 1:

Because b is an array of numbers, you can't meaningfully use + with it unless you want a comma-joined string. The most functional way to sum up an array is to use reduce, which can be used to iterate over its items and add them all to the accumulator:

b.reduce((a, b) => a + b);

If you want to know the partial sums, I'd use .map to transform each object in the employeeList array into the sum of their scores, by extracting the scores property and using reduce to sum them all up:

const employeeList=[{"name":"Ahmed","scores":["5","1","4","4","5","1","2","5","4","1"]},{"name":"Jacob Deming","scores":["4","2","5","1","3","2","2","1","3","2"]}]

constsum = (a, b) => Number(a) + Number(b);
const output = employeeList.map(({ scores }) => scores.reduce(sum));
console.log(output);
// If you want to sum up the results into a single number as well:console.log(output.reduce(sum));

Solution 2:

You can use array reduce to calculate the sum:

const employeeList = [    
{
  "name": "Ahmed",
  "scores": [
  "5",
  "1",
  "4",
  "4",
  "5",
  "1",
  "2",
  "5",
  "4",
  "1"
  ]
},
{
  "name": "Jacob Deming",
  "scores": [
  "4",
  "2",
  "5",
  "1",
  "3",
  "2",
  "2",
  "1",
  "3",
  "2"
  ]
}];

var sum = 0;

for(let i = 0; i < employeeList.length; i++){
  let eachScore = employeeList[i].scores;
  let b = eachScore.reduce((total,current)=>{
    total += +current;
    return total;
  },0);
  console.log(b);

  sum += b;
}

console.log(sum);

Solution 3:

Maybe this will help:

var parsedScores = [];
var scores = [
   "4","2","5","1","3","2","2","1","3","2"
];
let total = 0;
scores.forEach(el => {
   parsedScores.push(parseInt(el))
})
for (let score in parsedScores) {
   total += parsedScores[score]
}
console.log(total);

Post a Comment for "How To Get A The Sum Of Multiple Arrays Within An Array Of Objects?"