Return 哈希数组的平均值

Return an average from an array of hash

我刚开始使用 javascript 中的哈希,我想编写一个函数,它接受一个哈希数组和 returns class 的平均“等级”。

这是一个例子:

输入:

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

输出:9.5

提前致谢!

averagesum这样的操作最好使用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)

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)