为了账号安全,请及时绑定邮箱和手机立即绑定

返回哈希数组的平均值

返回哈希数组的平均值

www说 2023-03-24 15:30:10
我不熟悉在 javascript 中使用哈希,并且想编写一个函数,它接受一个哈希数组并返回一个类的平均“等级”。这是一个例子:输入:    {"string": "John", "integer": 7},    {"string": "Margot", "integer": 8},    {"string": "Jules", "integer": 4},    {"string": "Marco", "integer": 19}   输出:9.5提前致谢!
查看完整描述

2 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

平均值求和这样的操作最好使用一个Array.prototype.reduce()操作来完成。


您可以使用reduce产生一个总和,然后将该结果除以数组长度


const arr = [

  {"string": "John", "integer": 7},

  {"string": "Margot", "integer": 8},

  {"string": "Jules", "integer": 4},

  {"string": "Marco", "integer": 19}

]


const avg = arr.reduce((sum, hash) => sum + hash.integer, 0) / arr.length


console.info(avg)


查看完整回答
反对 回复 2023-03-24
?
狐的传说

TA贡献1804条经验 获得超3个赞

let items = [

    {"string": "John", "integer": 7},

    {"string": "Margot", "integer": 8},

    {"string": "Jules", "integer": 4},

    {"string": "Marco", "integer": 19}

]


let avg = items.reduce((a, b) => a + b.integer, 0) / items.length


console.log(avg)


查看完整回答
反对 回复 2023-03-24
  • 2 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号