【问题标题】:React/Javascript get max value of nested array in array of objectsReact / Javascript获取对象数组中嵌套数组的最大值
【发布时间】:2021-07-02 13:36:40
【问题描述】:

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

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

]

我想为 maxScore 值最高的玩家分配一个 Tag (antd)。我为此使用了以下代码:

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

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

感谢您的帮助!

【问题讨论】:

  • maxScore 和finish 值真的是字符串吗?不是数字吗?
  • 当有多个值时,作业不明确。请提供输入和预期输出的示例,尤其是当finishes 具有低值和高值时。
  • 我可以将字符串转换为数字,没关系,因为我不会使用这些值来计算东西或类似的东西

标签: javascript arrays reactjs object nested


【解决方案1】:

最高值:

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 和 finish 值都是一个数字。如果它们是字符串,则 Math.max 将在内部将它们转换为数字,因此 high-MaxScore 和 high-Finish 将是数字。所以为了让 team.find 和 team.filter 工作,它们必须被转换回字符串!

【讨论】:

  • 顺便说一句,我刚刚意识到 Math.max 不仅适用于数字,还适用于包含数字的字符串 :)
猜你喜欢
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2021-11-29
  • 2021-09-21
  • 2017-05-06
  • 1970-01-01
相关资源
最近更新 更多