Reputation: 147
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!
Upvotes: 1
Views: 2572
Reputation: 28698
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!
Upvotes: 1