简体   繁体   中英

React/Javascript get max value of nested array in array of objects

I'm currently using a function to assign custom tags based on the highest value in a small dataset. The dataset is as follows:

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

]

I wanted to assign a Tag (antd) to the player with the most maxScore value. I used the following code for that:

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

This worked fine, but now I want to do the same thing with the finishes. The main problem, the values are listed within an array. I can't figure out to modify the earlier used code to get the result I want.

Help is appreciated!

The highest values:

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

The team member with highest maxScore, and the team member with the highest finish:

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

If there can be more then one member with the highest value:

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

Note - My solution assumes that every maxScore and finishes value is a number. If they are strings, then Math.max will convert them to numbers internally, so highestMaxScore and highestFinish will be numbers. So in order to make team.find and team.filter work, they must be converted back to strings!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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