我创建了一组这样的元素:
$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)]
})
})
答案 0 :(得分:0)
我不清楚,如果你想找到一个团队和一个季节的价值,或者你想要总结一切。如果它是后者,那么这样的函数应该这样做:
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;
请注意,games
只需使用某些库中包含的groupBy
函数即可创建。使用Ramda(免责声明:我是Ramda作者),这将是
const games = R.groupBy(R.prop('season'), results)
使用Underscore或lodash,就像
const games = _.groupBy(results, _.property('season'))
但如果我在Ramda中这样做,我可能会完全采用不同的技术:
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;