Reputation: 3545
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
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