gpt4 book ai didi

javascript - 对象数组 - 计算属性的平均值?

转载 作者:行者123 更新时间:2023-11-28 11:20:37 25 4
gpt4 key购买 nike

所以我有这个对象数组

audioFeatures = [
{danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7},
{danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5},
{danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5},
{danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2},
]

我想计算每个属性的平均值,即可舞性应该 = (10+6+7+8)/4 等等。我已经通过大量的 for 循环完成了这项工作,但它似乎效率很低,我理想地希望最终得到一个包含我尚未弄清楚的平均值的对象。

有谁知道这样做的好方法。我正在用 JavaScript 进行编码,但任何建议都将不胜感激,我可以尝试实现它。我一直在尝试 map ,但不太清楚如何将其应用到此(也许嵌套 map 哈哈,这可能不是一个好主意)

最佳答案

你只需要两个for循环:

audioFeatures = [
{danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7},
{danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5},
{danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5},
{danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2},
]

const average = {};

for (const feature of audioFeatures) {
for (const [key, value] of Object.entries(feature)) {
if (!average[key]) average[key] = 0;
average[key] += value / audioFeatures.length;
}
}

console.log(average);

关于javascript - 对象数组 - 计算属性的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53214942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com