2 回答
TA贡献1842条经验 获得超21个赞
从这样的团队数组中获取 maxAverage:
this.state = {
homeCity: "Barcelona",
awayCity: "Valencia"
}
const scores = [
{ day: "1", Barcelona: 1, Real: 3, Valencia: 0 },
{ day: "2", Barcelona: 4, Real: 6, Valencia: 3 },
{ day: "3", Barcelona: 7, Real: 7, Valencia: 3 },
{ day: "4", Barcelona: 7, Real: 8, Valencia: 6 }
];
const getAverage = team => {
if (isNaN(scores[0][team])) return null;
return scores.map(x => x[team]).reduce((a, c) => a + c) / scores.length;
};
const maxAverage = teams => {
return teams.map(team => {
return {
team:team,
avg: getAverage(team)
}
}).reduce((a,b)=>a.avg>b.avg?a:b).team
}
console.log(maxAverage([this.state.homeCity,this.state.awayCity]));
TA贡献1833条经验 获得超4个赞
您可以扩展您的代码,循环遍历第一个元素以获取所有键,过滤出日期键,以便我们留下所有团队名称,映射团队名称并获取平均值然后进行排序
const scores = [
{ day: "1", Barcelona: 1, Real: 3, Valencia: 0 },
{ day: "2", Barcelona: 4, Real: 6, Valencia: 3 },
{ day: "3", Barcelona: 7, Real: 7, Valencia: 3 },
{ day: "4", Barcelona: 7, Real: 8, Valencia: 6 }
];
const getAverage = team => {
if (isNaN(scores[0][team])) return null;
return scores.map(x => x[team]).reduce((a, c) => a + c) / scores.length
};
let stronger = Object.entries(scores[0])
.filter(([key, value]) => key !== 'day')
.map(([key, value]) => [key, getAverage(key)])
.sort((a, b) => b[1] - a[1])
console.log(stronger)
添加回答
举报