简体   繁体   English

如何找到 map 中值的总和和平均值?

[英]How to find the sum and average of values in a map?

My goal is to add the numerical values in this map and divide them by the size of the map.我的目标是在这个 map 中添加数值,然后除以 map 的大小。 The result is merely the numbers without being added.结果只是没有添加的数字。 Here's how my code looks like as of the moment:这是我的代码目前的样子:

const problem2 = new Map();
problem2.set('Julie', 13);
problem2.set('Jojo', 10);
problem2.set('Polly', 10);
problem2.set('Jack', 10);
problem2.set('Bruce', 10);

let sum = "";
for (const value of problem2.values()){
   sum +=  parseInt (value, 10) +"\n";
};

sum; 

You can use forEach and size property您可以使用 forEach 和 size 属性

let sum = 0;
problem2.forEach(value => sum += value); // value is problem

let average = sum / problem2.size

You should not be concatenating the string "\n" and sum should be initialized to 0 as you are working with numbers.您不应该连接字符串"\n"并且sum在处理数字时应该初始化为0 The average is the sum divided by the number of values in the Map .平均值是总和除以Map中的值的数量。

 const problem2 = new Map(); problem2.set('Julie', 13); problem2.set('Jojo', 10); problem2.set('Polly', 10); problem2.set('Jack', 10); problem2.set('Bruce', 10); let sum = 0; for (const value of problem2.values()){ sum += value; }; console.log('Sum:',sum); console.log('Average:', sum / problem2.size);

Go with foreach over the map and sum up. Go 对 map 进行 foreach 并总结。 For avg divide through mapsize.对于通过 mapsize 进行平均划分。

 const problem2 = new Map(); problem2.set('Julie', 13); problem2.set('Jojo', 10); problem2.set('Polly', 10); problem2.set('Jack', 10); problem2.set('Bruce', 10); let sum = 0; problem2.forEach(value => sum += value); console.log('Sum: ' + sum); console.log('Average: ' + (sum / problem2.size));

You can convert the Map to an Array so you can use the Array.reduce method.您可以将Map转换为Array ,以便使用Array.reduce方法。

 const problem2 = new Map(); problem2.set('Julie', 13); problem2.set('Jojo', 10); problem2.set('Polly', 10); problem2.set('Jack', 10); problem2.set('Bruce', 10); const { sum, avg } = [...problem2] // convert Map to Array.reduce((result, [, value]) => { result.sum += value; result.avg = result.sum / problem2.size; return result; }, { sum: 0, avg: 0 }); console.log({ sum, avg }); // { sum: 53, avg: 10.6 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM