如何从对象数组中获取平均值 [英] How to get the average from array of objects

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

问题描述

下面,我复制我的代码以计算食物的平均评分.

Below I reproduce my code for calculate average ratings for foods.

3 + 4 + 5 + 2/4应该等于3.5. 但这不能给我正确的输出.我的代码有什么问题?

3+4+5+2 / 4 should be equal to 3.5. But this not gives me the correct output. What's wrong with my code?

const ratings = [
  {food:3},
  {food:4},
  {food:5},
  {food:2}
];

let food = 0;

ratings.forEach((obj,index)=>{
  food = (food + obj.food)/++index
})

console.log("FOOD",food)

推荐答案

尽管有几个答案,但我还是要重点关注我,以提高代码质量:

Despite of having several answers I would like to add mine focusing to improve the code quality:

  1. 您可以在forEach()中使用分解来获取对象的food属性,因为这只是您感兴趣的属性.
  2. 尽管在内部循环中进行划分,但在循环完成后,我们只能执行一次划分操作.当数组很大(成千上万个对象)时,这样可以节省大量计算
  3. 您可以在循环中使用像+=这样的短手来求和.
  4. 您可以在forEach()
  5. 中创建一行代码
  1. You can use destructuring in forEach() to just get the food property of the object as that is only the property you are interested with.
  2. Despite of dividing inside loop we can have only one division operation after the loop is completed. This saves a lot of computation when the array is huge(thousands of objects)
  3. You can use short hand like += in the loop for summing up the value.
  4. You can make a single line code in forEach()

const ratings = [
  {food:3},
  {food:4},
  {food:5},
  {food:2}
];

let foodTotal = 0;
let length = ratings.length;
ratings.forEach(({food})=> foodTotal += food);

console.log("FOOD",foodTotal/length);

这篇关于如何从对象数组中获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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