我正在嘗試計算物件陣列中具有相同鍵的值的平均值。并非所有物件都包含與其他物件相同的值,但我仍然希望根據它在陣列中出現的次數回傳平均值。例如我想要
const Object1 = [{
2005: 5.6,
2006: 5.2
}, {
2005: 5.6,
2006: 5.7,
2007: 5.4
}, {
2005: 5.6,
2006: 5.9,
2007: 5.8
}]
回傳
{
2005: 5.599999999999999,
2006: 5.6000000000000005,
2007: 5.6
}
這是我到目前為止所嘗試的。現在的問題是我無法 / 它出現的次數。如果它缺少年份,則該值將變為未定義,這將導致結果為 NaN。
const Object1 = [{
2005: 5.6,
2006: 5.2
}, {
2005: 5.6,
2006: 5.7,
2007: 5.4
}, {
2005: 5.6,
2006: 5.9,
2007: 5.8
}]
const years = Object.keys(Object.assign({}, ...Object1));
const Result = years.reduce((a, v) => ({
...a,
[v]: v
}), {})
console.log(Result)
years.map((year) => {
const value =
Object1.map(function(obj) {
return obj[year]
}).reduce(function(a, b) {
return (a b)
}) / years.length
Result[year] = value
})
console.log(Result)
uj5u.com熱心網友回復:
const Object1 = [{
2005: 5.6,
2006: 5.2
}, {
2005: 5.6,
2006: 5.7,
2007: 5.4
}, {
2005: 5.6,
2006: 5.9,
2007: 5.8
}]
const years = Object.keys(Object.assign({}, ...Object1));
const Result = years.reduce((a, v) => ({
...a,
[v]: v
}), {})
console.log(Result)
years.map((year) => {
var filteredYear = Object1.map(function(obj) {
return obj[year]
}).filter(e=>e!=undefined)
const value =
filteredYear.reduce(function(a, b) {
return (a b)
}) / filteredYear.length
Result[year] = value
})
console.log(Result)
uj5u.com熱心網友回復:
您可以按年份對積分進行分組,并僅根據每個分組計算積分
const object1 = [
{
2005: 5.6,
2006: 5.2,
},
{
2005: 5.6,
2006: 5.7,
2007: 5.4,
},
{
2005: 5.6,
2006: 5.9,
2007: 5.8,
},
];
const groupPointByYears = object1.reduce((map, obj) => {
for (const [year, point] of Object.entries(obj)) {
if (!map.has(year)) {
map.set(year, []);
}
map.get(year).push(point);
}
return map;
}, new Map());
console.log(Array.from(groupPointByYears));
const res = Object.fromEntries(
Array.from(groupPointByYears).map(([year, points]) => [
year,
points.reduce((sum, point) => sum point, 0) / points.length,
])
);
console.log(res);
uj5u.com熱心網友回復:
const years = Object1.reduce(( prev, curr ) => {
for (const key in curr) prev[key] = (prev[key] || []).concat(curr[key])
return prev
}, {})
const Result = {}
for (const year in years) {
avg[year] = years[year].reduce(( prev, val ) => prev val, 0) / years[year].length
}
這段代碼首先將每年的所有值放在一個物件的陣列中(這是第一個 reduce 所做的)然后它每年回圈并將平均值(所有值的總和除以值的數量)添加到 Result 物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459796.html
標籤:javascript 节点.js 数组 目的
