Tonald Drump
Tonald Drump

Reputation: 1386

Javascript: Find maximum value of object property in array in object in array :D

I have the following array of objects and I want to find the highest weight of any person in any year (the weight is enough, I don't need the corresponding year or name).

Thanks in advance :)

var arr = [
    {
        'name': 'Bob',
        'weights': [
            {
                'weight': 90,
                'year': 2018
            },
            {
                'weight': 85,
                'year': 2017
            },
            // etc.
        ]
    },
        'name': 'Charlie',
        'weights': [
            {
                'weight': 65,
                'year': 2018
            },
            {
                'weight': 60,
                'year': 2017
            },
            // etc.
        ]
    },
    // etc.
]

Upvotes: 0

Views: 76

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122145

You could use Math.max and spread syntax to find max value but you also need to use map to get weight values in one array first.

var arr = [{"name":"Bob","weights":[{"weight":90,"year":2018},{"weight":85,"year":2017}]},{"name":"Charlie","weights":[{"weight":65,"year":2018},{"weight":60,"year":2017}]}]

var max = Math.max(...[].concat(...arr.map(({weights}) => weights.map(({weight}) => weight))))
console.log(max)

Upvotes: 3

Related Questions