[英]How do I group by one element and find the average of another in Javascript?
我正在做一個項目,將葡萄酒的年齡與其分數進行比較,並希望制作一個折線圖,X 軸為年齡,Y 軸為每個年齡的平均分數。我有一個對象數組,每個對象包含兩個元素,年齡和score 並希望按每個年齡分組並找到該年齡的平均分數。
我通過執行來自 Global Wine Score 的請求創建了一個 CSV 文件,其中包含年份、審查日期、分數等。在 python 中,我通過從年份中減去審查年份創建了一個年齡列。 在 Javascript 中,我創建了一個新數組:
var newArr = countryFilter.map(function(elem) {
return {
age: elem.wine_age,
score: elem.score
};
});
這是我的數組的樣子:
0: Object { age: "116", score: "98.51" }
age: "116"
score: "98.51"
1: Object { age: "113", score: "84.46" }
age: "113"
score: "84.46"
length: 23258
我試過了,但是任何具有超過 1 個唯一分數的對象都會產生 NAN。
const reduced = newArr.reduce(function(m, d){
if(!m[d.age]){
m[d.age] = {...d, count: 1};
return m;
}
m[d.age].score += d.score;
m[d.age].count += 1;
return m;
},{});
const result = Object.keys(reduced).map(function(k){
const item = reduced[k];
return {
wine_age: item.age,
score: item.score/item.count,
}
})
console.log(result);
我將如何找到每個酒齡的平均葡萄酒分數?
您可以按年齡將子數組中的對象分組,然后將子數組減少為具有平均分數的單個對象:
const input = [ { age: "113", score: "84.46" }, { age: "113", score: "88.23" }, { age: "112", score: "84.46" }, { age: "113", score: "10.58" }, ]; const result = input .sort((a, b) => a.age - b.age) .reduce( (acc, cur, i, { [i - 1]: last }) => cur.age === last?.age ? Object.assign([...acc], { [acc.length - 1]: [...acc[acc.length - 1], cur], }) : [...acc, [cur]], [] ) .map((x) => ({ age: x[0].age, score: x.reduce((a, b) => a + Number(b.score), 0) / x.length, })); console.log(result);
這是獲取它的一種方法。 你最終會得到一個 age:average 對的對象:
let grps={}
data.forEach(g => grps.hasOwnProperty(g.age)? // first we set up the age -> array of scores object
grps[g.age].push(+g.score) : grps[g.age] = [+g.score]),
avgs = Object.assign(...Object.entries(grps) // then we take that object and calculate the avg based on the total score tally / number of scores
.map(g=>({[g[0]]:
(g[1].reduce((b,a)=> b+a)/grps[g[0]].length).toFixed(2)}))) // reduce is a perfect vehicle for tallying up arrays of numbers.
let data = [ { age: "113", score: "84.46" }, { age: "113", score: "88.23" }, { age: "112", score: "84.46" }, { age: "113", score: "10.58" }, ] let grps={}, s = data.forEach(g=>grps.hasOwnProperty(g.age)?grps[g.age].push(+g.score) : grps[g.age] = [+g.score]), avgs = Object.assign(...Object.entries(grps).map(g=>({[g[0]]:(g[1].reduce((b,a)=> b+a)/grps[g[0]].length).toFixed(2)}))) console.log(avgs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.