假设我们有一个数组,其中包含一些不同运动项目的得分。分数表示如下:
const scores = [ {sport: 'cricket', aman: 54, vishal: 65, jay: 43, hardik: 88, karan:23}, {sport: 'soccer', aman: 14, vishal: 75, jay: 41, hardik: 13, karan:73}, {sport: 'hockey', aman: 43, vishal: 35, jay: 53, hardik: 43, karan:29}, {sport: 'volleyball', aman: 76, vishal: 22, jay: 36, hardik: 24, karan:47}, {sport: 'baseball', aman: 87, vishal: 57, jay: 48, hardik: 69, karan:37}, ];
我们必须编写一个函数,该函数接受此数组并返回单个对象,该对象的运动键值为“ all”,其他玩家键的值之和应存在于数组的不同对象中。因此,让我们为该函数编写代码-
我们将在此处使用Array.prototype.reduce()方法来减少所有玩家在不同运动项目中的得分总和。这样做的代码将是-
const scores = [ {sport: 'cricket', aman: 54, vishal: 65, jay: 43, hardik: 88, karan:23}, {sport: 'soccer', aman: 14, vishal: 75, jay: 41, hardik: 13, karan:73}, {sport: 'hockey', aman: 43, vishal: 35, jay: 53, hardik: 43, karan:29}, {sport: 'volleyball', aman: 76, vishal: 22, jay: 36, hardik: 24, karan:47}, {sport: 'baseball', aman: 87, vishal: 57, jay: 48, hardik: 69, karan:37}, ]; const sumScores = (arr) => { return arr.reduce((acc, val) => { Object.keys(val).forEach(key => { if(key!== 'sport'){ acc[key] += val[key]; }; }); if(acc['sport'] !== 'all'){ acc['sport'] = 'all'; }; return acc; }); }; console.log(sumScores(scores));
输出结果
控制台中的输出将为-
{ sport: 'all', aman: 274, vishal: 254, jay: 221, hardik: 237, karan: 209 }