Paulos3000
Paulos3000

Reputation: 3545

Calculate object with highest value property in multidimensional array

I have an multilayered array in which I want to calculate the object which contains the highest value of a specific property.

let arr = [{
    id: 1,
    card: {
        firstName: 'John',
        lastName: 'Smith',
        info: {
            age: 36,
            height: 152
        }
    }
}, {
    id: 2,
    card: {
        firstName: 'Dan',
        lastName: 'Hislop',
        info: {
            age: 38,
            height: 155
        }
    }
}, {
    id: 3,
    card: {
        firstName: 'Mary',
        lastName: 'Walter',
        info: {
            age: 29,
            height: 122
        }
    }
}]

I want to be able to calculate the top level object in that array that contains the highest age value, and returns that object.

The best I can do at the moment is find the highest value and return that value alone:

let oldest = Math.max.apply(Math, arr.map(obj =>
  obj.card.info.age) )

But I want the whole object.

Any help appreciated.

Upvotes: 1

Views: 91

Answers (2)

user1636522
user1636522

Reputation:

A good old for loop looks perfect to me :

var i, xs, max;
xs = [{value:3},{value:1},{value:4},{value:2}];
for (i = 0; i < xs.length; i++) {
  if (i == 0 || xs[i].value > xs[max].value) {
    max = i;
  }
}
console.log(xs[max]);

Upvotes: 1

fafl
fafl

Reputation: 7387

This is a case for reduce:

arr.reduce((prev, curr) => prev.card.info.age < curr.card.info.age ? curr : prev)

Nothing magical about it, we just look at two objects at a time and continue with the one which has the higher age.

Upvotes: 1

Related Questions