'How to get max value of nested array in array of objects (with an extra condition)

const highestFinish = Math.max(...team.flatMap(member => member.finishes));
const team = [
    { name: 'John Doe', finishes: ['105', '108'] },
    { name: 'Peter Pie', finishes: ['140'] }
]

This solution works for determing the highest value, but supposed I want to have a specific index inside the finishes array how would I get the max value give the index. For example, if the index is 1, it should return 108, if the index is 0, it should return 140. How can i change the given function to acheive this?



Solution 1:[1]

You can map to the i-th element instead of flatMap and filter out undefined:

const team = [
    { name: 'John Doe', finishes: ['105', '108'] },
    { name: 'Peter Pie', finishes: ['140'] }
]
const highestFinish = (i) => Math.max(...team.map(member => member.finishes[i]).filter(el => el !== undefined));

console.log(highestFinish(0));
console.log(highestFinish(1));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jabaa