从哈希数组返回平均值

时间:2020-09-23 23:43:14

标签: javascript arrays hashmap hashtable average

我是刚开始使用javascript进行哈希处理,并且想编写一个函数,该函数接受一个哈希数组并返回一个类的平均“等级”。

这里是一个例子:

输入:

    {"string": "John", "integer": 7},
    {"string": "Margot", "integer": 8},
    {"string": "Jules", "integer": 4},
    {"string": "Marco", "integer": 19}
   

输出:9.5

谢谢!

2 个答案:

答案 0 :(得分:3)

最好使用Array.prototype.reduce()操作来完成 average sum 之类的操作。

您可以使用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)

答案 1 :(得分:-2)

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)

相关问题