gpt4 book ai didi

javascript - 迭代 javascript 数据对象并查找平均值的最佳方法

转载 作者:行者123 更新时间:2023-11-28 13:05:50 27 4
gpt4 key购买 nike

我正在尝试迭代一个对象并显示对象内每个键的平均值。

假设我有:

data = {
totals: {
item1: {
time: 15,
speed: 20,
amount: 12,
units: 29
},
item2: {
time: 3,
speed: 75,
amount: 14,
units: 3
},
item3: {
time: 19,
speed: 4,
amount: 44,
units: 365
}
}
}

创建这些值的平均值的最佳方法是什么:

averages = {
time: 12,
speed: 33,
amount: 40,
units: 132
}

我知道将每个键值的总和除以总项目数,但我正在努力寻找一种好方法来迭代每个项目并将总数相加。这些项目将根据每个帐户的条目动态创建。

使用 for .. in 循环是最好的方法吗?如果是这样,我将如何使用它来实现这一目标?像下面这样的东西?

function findAverage() {
const averages = {
time: 0,
speed: 0,
amount: 0,
units: 0
}

const totalItems = Object.keys(data.totals).length

for (item in data.totals) {
averages.time += item.time;
averages.speed += item.speed;
averages.amount += item.amount;
averages.units += item.units;
}

averages.time = averages.time / totalItems;
averages.speed = averages.speed / totalItems;
averages.amount = averages.amount / totalItems;
averages.units = averages.units / totalItems;

return averages;
}

有没有更好的方法来解决这个问题?我完全不做我在这里想做的事情吗?

最佳答案

您可以使用 Object.keys 和数组上的 reduce 方法来代替循环

function calculateAverage(totals) {
const items = Object.keys(totals).reduce((result, item) => result.concat(totals[item]), [])
const itemsCount = items.length;

const metricsTotals = items.reduce((sums, item) => {
sums.time += item.time
sums.speed += item.speed
sums.amount += item.amount
sums.units += item.units
return sums
}, { time: 0, speed: 0, amount: 0, units: 0})

return Object.keys(metricsTotals).reduce((average, metric) => {
average[metric] = Math.floor(metricsTotals[metric] / itemsCount)
return average
}, {})
}

var data = {
totals: {
item1: {
time: 15,
speed: 20,
amount: 12,
units: 29
},
item2: {
time: 3,
speed: 75,
amount: 14,
units: 3
},
item3: {
time: 19,
speed: 4,
amount: 44,
units: 365
}
}
}


const averages= calculateAverage(data.totals)
console.log(averages)

关于javascript - 迭代 javascript 数据对象并查找平均值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551962/

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