1

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!

3
  • 1
    Are maxScore and finishes values really strings? Aren't they numbers? Commented Jul 2, 2021 at 13:41
  • When there are multiple values, the job is ambiguous. Please provide examples of input and expected output, especially when finishes has both low and high values. Commented Jul 2, 2021 at 13:42
  • I could convert the strings to numbers, doesn't matter since I will not use these values to count stuff or something like that Commented Jul 2, 2021 at 13:43

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

By the way, I've just realized that Math.max works not just with numbers, but also with strings which contain numbers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.