Search code examples
javascriptarraysobjectarray-map

JavaScript: find Object with highest summed values from Array


In need the Object with maximum a+b value from myArray

var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];

Right now I have something that returns me the index:

var max = [], maxIndex;
myArray.map(x=>max.push(x.a + x.b))
maxIndex = max.indexOf( Math.max.apply(Math, max))

I need something that returns the Object and not its index, so far working with

var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y)

returning false.


Solution

  • No need for map as reduce will itterate over you array.

    var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
    
    
    var biggestSumObj = myArray.reduce((total,current)=>{
      if((current.a + current.b) > (total.a + total.b)){
        return current;
      }
      return total;
    });
    
    
    console.log(biggestSumObj);
    

    fiddle: return biggest object