繁体   English   中英

React/Javascript 获取对象数组中嵌套数组的最大值

[英]React/Javascript get max value of nested array in array of objects

我目前正在使用一个函数根据小数据集中的最高值分配自定义标签。 数据集如下:

const team = [
    { name: 'John Doe', maxScore: '2', finishes: ['105', '108'] },
    { name: 'Peter Pie', maxScore: '1', finishes: ['140'] }

]

我想为具有最大 maxScore 值的玩家分配一个标签(antd)。 我为此使用了以下代码:

const highestMaxScore = Math.max.apply(
        Math,
        team.map(function (t) {
            return t.maxScore
        })
    )

这工作得很好,但现在我想对饰面做同样的事情。 主要问题是,这些值列在一个数组中。 我想不出修改之前使用的代码来获得我想要的结果。

帮助表示赞赏!

最高值:

const highestMaxScore = Math.max(...team.map(member => member.maxScore));
const highestFinish = Math.max(...team.flatMap(member => member.finishes));

maxScore 最高的队员,以及成绩最高的队员:

const memberWithHighestMaxScore = team.find(member => member.maxScore === highestMaxScore);
const memberWithHighestFinish = team.find(member => member.finishes.includes(highestFinish));

如果可以有多个具有最高值的成员:

const membersWithHighestMaxScore = team.filter(member => member.maxScore === highestMaxScore);
const membersWithHighestFinish = team.filter(member => member.finishes.includes(highestFinish));

注意- 我的解决方案假定每个 maxScore 和完成值都是一个数字。 如果它们是字符串,那么 Math.max 会在内部将它们转换为数字,因此 highmaxMaxScore 和highestFinish 将是数字。 因此,为了使 team.find 和 team.filter 工作,必须将它们转换回字符串!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM