如何获得一个对象数组中多个数组的总和? [英] How to get a the sum of multiple arrays within an array of objects?

查看:99
本文介绍了如何获得一个对象数组中多个数组的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何获取对象数组中多个数组的总和.我的代码如下:

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": [
    "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++){
  var eachScore = employeeList[i].scores;
  const b = eachScore.map(Number);
  console.log(b);

  sum += parseInt(b);//this is the code that doesn't work

}

console.log(sum);

所以问题是,我可以将两个数组放入控制台日志,但是我不确定如何对每个数组求和..当我执行sum + = parseInt(b)时,它只会记录多少个项目在array(9)中.当我不使用parseInt时,它会将数字合并在一起,但不将它们求和..我想使用.split()方法拆分数组并将它们分别求和,但我还没有弄清楚做到这一点.

So the problem is, I can get the two arrays to console log but I'm not sure how to go about summing up each array.. When I do sum += parseInt(b), it just logs how many items are in the array(9). and When I do without parseInt, it concats the numbers together but doesn't sum them up.. I would like to use a .split() method to split the arrays and sum them up individually but I haven't quite figured out how to do it yet.

推荐答案

由于 b 是一个数字数组,除非您不使用 + ,否则无法对其进行有意义的使用需要一个逗号连接的字符串.总结数组最实用的方法是使用 reduce ,可用于迭代其项并将其全部添加到累加器中:

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);

如果您想知道部分和,我将使用 .map employeeList 数组中的每个对象转换为它们的分数总和,方法是提取 scores 属性,并使用 reduce 汇总它们:

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

const sum = (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));

这篇关于如何获得一个对象数组中多个数组的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆