在javascript中从列表中求和元素

时间:2018-05-08 15:32:09

标签: javascript

我创建了一组这样的元素:

$ReadOnly<T>

我想总结季节(2007年的情况)中的所有观点。为此,我尝试使用此功能....功能有问题......任何想法是什么问题?

const teamRecords = [
  {
    team: 'A',
    results: [
      { season: '2007', game: 'G1', points: 3 }
      { season: '2007', game: 'g2', points: 3 }
      // ...
    ]
  }
]

最后我想有这个清单:

 var results;

 result.forEach(s => {
        result[s].forEach(Season=>{
            results[s].Points = [Season.map(Game => Points).reduce((a,b)=>a+b)]
        })
    })

1 个答案:

答案 0 :(得分:0)

我不清楚,如果你想找到一个团队和一个季节的价值,或者你想要总结一切。如果它是后者,那么这样的函数应该这样做:

&#13;
&#13;
const seasonSummary = (teamRecords) => teamRecords.map(({team, results}) => {
  const games = results.reduce((all, curr) => {
    if (!(curr.season in all)) {all[curr.season] = 0;}
    all[curr.season] += curr.points
    return all
  }, {})
  return {team, results: Object.keys(games).map(season => ({season, points: games[season]}))}
})


const teamRecords = [{
  team: 'A',
  results: [
    { season: '2007', game: 'g1', points: 3 },
    { season: '2007', game: 'g2', points: 3 },
    { season: '2008', game: 'g1', points: 2 },
  ]
}, {
  team: 'B',
  results: [
    { season: '2007', game: 'g1', points: 1 },
    { season: '2008', game: 'g1', points: 5},
    { season: '2008', game: 'g2', points: 2},
  ]
}]

const summary = seasonSummary(teamRecords)

console.log(summary)
&#13;
&#13;
&#13;

请注意,games只需使用某些库中包含的groupBy函数即可创建。使用Ramda(免责声明:我是Ramda作者),这将是

const games = R.groupBy(R.prop('season'), results)

使用Underscorelodash,就像

const games = _.groupBy(results, _.property('season'))

但如果我在Ramda中这样做,我可能会完全采用不同的技术:

&#13;
&#13;
const {map, evolve, pipe, groupBy, prop, pluck, sum, toPairs, zipObj} = R;

const seasonSummary = map(evolve({
  results: pipe(
    groupBy(prop('season')),
    map(pluck('points')),
    map(sum),
    toPairs,
    map(zipObj(['season', 'points']))
  )
}))

const teamRecords = [{"results": [{"game": "g1", "points": 3, "season": "2007"}, {"game": "g2", "points": 3, "season": "2007"}, {"game": "g1", "points": 2, "season": "2008"}], "team": "A"}, {"results": [{"game": "g1", "points": 1, "season": "2007"}, {"game": "g1", "points": 5, "season": "2008"}, {"game": "g2", "points": 2, "season": "2008"}], "team": "B"}]

console.log(seasonSummary(teamRecords))
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
&#13;
&#13;
&#13;