我想知道如何获取对象数组中多个数组的总和。我的代码如下:
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()方法拆分数组并将它们分别求和,但我还没有弄清楚做到这一点。
答案 0 :(得分:0)
由于b
是一个数字数组,因此除非您需要逗号连接的字符串,否则您无法将+
与它配合使用。总结数组的最实用方法是使用reduce
,该数组可用于迭代其项并将其全部添加到累加器中:
b.reduce((a, b) => a + b);
如果您想知道部分和,我将使用.map
通过提取employeeList
属性并将scores
数组中的每个对象转换为其分数总和。使用reduce
对它们进行总计:
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));
答案 1 :(得分:0)
您可以使用array reduce来计算总和:
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);
答案 2 :(得分:0)
也许这会有所帮助:
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);