gpt4 book ai didi

javascript - 如何找到数组中相似对象的平均值并将它们输出到一个对象中?

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

我有一个具有这种结构的对象数组:

    [
costBreakdown: {
flexMeetAncCost: "1,274,051",
flexOneTimeCosts: "0",
flexSeatCharges: "2,403,869",
tradFacilMgmtCost: "134,437",
tradOneTimeTotalCost: "1,462,049",
tradRentCost: "1,572,738",
},

costBreakdown: {
flexMeetAncCost: "1,279,524",
flexOneTimeCosts: "0",
flexSeatCharges: "2,414,197",
tradFacilMgmtCost: "135,025",
tradOneTimeTotalCost: "1,467,029",
tradRentCost: "1,579,576",
},
]

并且我试图遍历所有这些对象并在解析字符串后找到每个键的平均值并使其成为整数,然后输出聚合的一个对象。

const { mean } = require('lodash')

const result = allLambdas.reduce((acc, currValue, index, array) => {
const aggregateCostBreakdown = (key) => (
Math.round(mean(array.map((obj) => parseFloat(obj.costBreakdown[key].replace(/,/g, ''))))).toLocaleString('en')
)

const avgCostBreakdown = {
flexMeetAncCost: aggregateCostBreakdown('flexMeetAncCost'),
flexOneTimeCosts: aggregateCostBreakdown('flexOneTimeCosts'),
flexSeatCharges: aggregateCostBreakdown('flexSeatCharges'),
tradFacilMgmtCost: aggregateCostBreakdown('tradFacilMgmtCost'),
tradOneTimeTotalCost: aggregateCostBreakdown('tradOneTimeTotalCost'),
tradRentCost: aggregateCostBreakdown('tradRentCost')
}

acc.costBreakdown = avgCostBreakdown

return acc
}, {
costBreakdown: {},
}
)

虽然这看起来可行,但我认为我不应该在 reduce 函数中引用 array 参数,因为这似乎性能不佳。

如何获取这些对象数组的平均值并将它们输出到一个对象中?

最佳答案

您可以尝试这样的事情,首先对值求和并保持计数,然后找到每个 Prop 的平均值。希望这会有所帮助。

const data = [{
costBreakdown: {
flexMeetAncCost: "1,274,051",
flexOneTimeCosts: "0",
flexSeatCharges: "2,403,869",
tradFacilMgmtCost: "134,437",
tradOneTimeTotalCost: "1,462,049",
tradRentCost: "1,572,738",
} },{
costBreakdown: {
flexMeetAncCost: "1,279,524",
flexOneTimeCosts: "0",
flexSeatCharges: "2,414,197",
tradFacilMgmtCost: "135,025",
tradOneTimeTotalCost: "1,467,029",
tradRentCost: "1,579,576",
},
}
];

const findMeans = (arr) => {

const summed = arr.reduce((acc, { costBreakdown }) => {

Object.keys(costBreakdown).forEach((key) => {

const n = parseFloat(costBreakdown[key].replace(',', '.'));

acc.costBreakdown[key] = acc.costBreakdown[key] ? { value: acc.costBreakdown[key].value + n, count: acc.costBreakdown[key].count + 1 } : { value: n, count: 1 }
});

return acc;

}, { costBreakdown: {} });

return Object.keys(summed.costBreakdown).reduce((acc, val) => {

acc.costBreakdown[val] = summed.costBreakdown[val].value / summed.costBreakdown[val].count;

return acc;

}, { costBreakdown: {} });
};

console.log(findMeans(data));

关于javascript - 如何找到数组中相似对象的平均值并将它们输出到一个对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066450/

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