首页 > 解决方案 > 仅对那些使用 map 通过条件的元素求和

问题描述

我有两个数组:
teamA = [97, 112, 101]
teamB = [109, 95, 123]

数组中的每个元素都是特定球队在一场比赛中的得分。我需要设置一个条件,仅将高于 100 的分数相加。因此,对于一个团队来说,条件是:如果团队得分高于 100,则该团队的得分与另一个也高于 100 的团队的总和,并且如果该分数的总和更高比另一队得分之和,该队获胜。

我认为通过映射我可以得到高于 100 的分数,但是我得到了一个新数组,其中第一个元素是未定义的。

我的代码示例:

const dolphinsGames = [97, 112, 101];
const koalasGames = [109, 95, 123];

const dolphinsScoreAbove = dolphinsGames.map((dolphinsGame) => {
if (dolphinsGame >= 100) {
    return dolphinsGame;
}
});
const koalasScoreAbove = koalasGames.map((koalasGame) => {
if (koalasGame >= 100) {
   return koalasGame;
}
});

结果是: 在此处输入图像描述

标签: javascriptarraysconditional-statements

解决方案


Array#map返回一个与数组长度相同的新数组,并获取每个项目的回调结果。

相反,您可以使用Array#filterwhich 过滤数组并返回或不返回项目,具体取决于过滤器函数。

const
    valid = score => score >= 100,
    add = (a, b) => a + b,
    dolphinsGames = [97, 112, 101],
    koalasGames = [109, 95, 123],
    dolphinsScore = dolphinsGames.filter(valid).reduce(add, 0),
    koalasScore = koalasGames.filter(valid).reduce(add, 0);

console.log(dolphinsScore, koalasScore);

if (dolphinsScore === koalasScore) console.log('draw');
else if (dolphinsScore > koalasScore) console.log('dolphins won');
else console.log('koalas won');


推荐阅读