【问题标题】:Return an average from an array of hash从哈希数组返回平均值
【发布时间】:2020-09-23 23:43:14
【问题描述】:

我是在 javascript 中使用哈希的新手,我想编写一个函数,它接受一个哈希数组并返回一个类的平均“等级”。

这是一个例子:

输入:

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

输出:9.5

提前致谢!

【问题讨论】:

  • 你有什么问题?
  • @JaromandaX:我相信他会的。这不是问题。

标签: javascript arrays hashmap hashtable average


【解决方案1】:

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)

【讨论】:

    【解决方案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)

    【讨论】:

    • 不知道为什么您的原始答案被否决了。除了不处理零长度数组之外,这对我来说似乎是正确的。
    • @slappy 我认为它在制作[object Object]8419时遭到了一些反对票
    • @Phil:我一定是错过了那个版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多