brunodbo brunodbo - 3 months ago 6
Javascript Question

How to get object with largest property from array?

I have an array of objects, with each object containing other 'subobjects'. I need to return the subobject with the largest 'quality' property.

The code below logs out all subobjects. How do I only return the one with the largest quality?



var maxQuality = function(Arr) {
Arr.forEach(function(obj, index) {
Math.max.apply(Math, obj.products.map(function(subObj) {
console.log(subObj);
}))
});
},
store = [
{
products: [
{
quality: 1,
info: 'info 1'
},
{
quality: 2,
info: 'info 2'
},
{
quality: 3,
info: 'info 3'
}
]
}
],
maxQualityProduct = maxQuality(store);




Answer

Although the other .reduce answer probably gives you what you need, if the store array were to contain more than one object - not sure if that is something you will want/need - you could use this:

var maxQuality = function(storeArray) {
    function highestQuality(prev, curr) {
        return prev.quality > curr.quality ? prev : curr
    }

    return storeArray.map(function(obj) {
      return obj.products.reduce(highestQuality)
    }).reduce(highestQuality);
}