javascript - 仅对那些使用 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;
}
});
结果是: 在此处输入图像描述
解决方案
Array#map
返回一个与数组长度相同的新数组,并获取每个项目的回调结果。
相反,您可以使用Array#filter
which 过滤数组并返回或不返回项目,具体取决于过滤器函数。
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');
推荐阅读
- visual-studio-code - vscode中option-n的奇怪行为
- apache-spark - databricks spark - 集群本身是性能低下的原因吗?
- python - 将数据帧值转换为不为空的 str(无)
- r - R的nlme中的二次函数实现错误
- tableau-api - Tableau 运行占总数的百分比
- python-3.x - 将 numpy.array 编码和解码为 base64。为什么需要使用 numpy.frombuffer?
- php - 使用 Google Drive 的服务帐户而不是 OAuth 时,“客户端未经授权无法使用此方法检索访问令牌”
- sql - SQL - 我有两个日期字符串,即返回 len(9)、m/dd/yyyy 和 mm/d/yyyy。什么有助于选择格式?
- javascript - 使用 Javascript 查找可以在列表中找到的元素的属性值,如果该值存在,则将一个类添加到它的一些子项中?
- c++ - 需要关于 C++ 中向量的帮助;