计算不同数组中对象之间的较大值

我有一个score包含两个对象的数组:Liga和Premier。这 2 个对象是一组团队列表。


当score以前是单个对象数组时,我能够定义更大的字符串。


这是我复制的演示,比较工作正常。


这是计算比较 2 个对象的较高值的代码。


const maxAverage = teams => {

  return teams.map(team => {

      return {

          team:team, 

          avg: getAverage(team)

      }

  }).reduce((a,b)=>a.avg>b.avg?a:b).team

}



<p>Stronger Team:{maxAverage([this.state.homeCity,this.state.awayCity])</p>

现在的问题是,现在score是我所说的 2 个对象的数组,我正在尝试以类似的方式更改我的函数


const maxAverage = (league, teams) => {

  return teams.map(team => {

      return {

          team:team,

          avg: getAverage(league,team)

      }

  }).reduce((a,b)=>a.avg>b.avg?a:b).team

}

我无法将maxAverage所选的两个联赛之一的参数传递给我的函数,然后是我想要比较的 2 个对象(球队)。


我想做这样的事情:


<p>Stronger Team:{maxAverage([this.state.selectedLeague], this.state.selectedHomeTeam,this.state.selectedAwayTeam])}

这是我在当前情况下复制的另一个演示。


慕少森
浏览 103回答 3
3回答

暮色呼如

我查看了您的第二个演示,我认为您有两种选择来选择正确的团队,并且您可以对两者重复使用以前的 getAverage 方法。任何一个&nbsp; const maxAverage = (league, teams) => {&nbsp; const currentLeague = [scores][0][league]&nbsp; return teams&nbsp; &nbsp; .map(team => {&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; team: team,&nbsp; &nbsp; &nbsp; &nbsp; avg: getAverage(currentLeague, team)&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; })&nbsp; &nbsp; .reduce((a, b) => (a.avg > b.avg ? a : b)).team;};或者,您可以保留原始 maxAverage 代码并更改实现联赛值的方式,例如。&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Stronger Team:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {maxAverage(scores[this.state.selectedLeague], [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.selectedHomeTeam,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.selectedAwayTeam&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ])}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </p>

当年话下

什么是问题?const scores = {'liga':[&nbsp; { day: "1", Barcelona: 1, Real: 3, Valencia: 0 },&nbsp; { day: "2", Barcelona: 4, Real: 6, Valencia: 3 },&nbsp; { day: "3", Barcelona: 7, Real: 7, Valencia: 3 },&nbsp; { day: "4", Barcelona: 7, Real: 8, Valencia: 6 }], 'primier':[&nbsp; { day: "1", Barcelona: 1, Real: 3, Valencia: 0 },&nbsp; { day: "2", Barcelona: 4, Real: 6, Valencia: 3 },&nbsp; { day: "3", Barcelona: 7, Real: 7, Valencia: 3 },&nbsp; { day: "4", Barcelona: 7, Real: 8, Valencia: 6 }]};const getAverage = (type, team) => {&nbsp; if (isNaN(scores[type][0][team])) return null;&nbsp; return scores[type].map(x => x[team]).reduce((a, c) => a + c) / scores[type].length;};getAverage('liga',this.state.homeCity);源代码:https : //codesandbox.io/s/recharts-examples-d9qy0

小怪兽爱吃肉

给定签名const maxAverage = (league, teams) => ...,以下代码将匹配预期的参数(但不确定业务逻辑):maxAverage(&nbsp; this.state.selectedLeague,&nbsp; [this.state.selectedHomeTeam, this.state.selectedAwayTeam])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript