简体   繁体   中英

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 .

You can use reduce like below

 var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; const finalResult = myArray.reduce((result, obj) => { let sum = obj.a + obj.b; if(result.sum < sum) { return {sum, obj: {...obj}} } return result; }, {sum: 0, obj: {}}) console.log(finalResult.obj)

Hope this helps.

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

You may try something like that:

 let myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; let max = myArray[0].a + myArray[0].b; let maxObject = {...myArray[0]}; myArray.map((obj) => { if(max < obj.a + obj.b) { max = obj.a + obj.b; maxObject = {...obj} } }); console.log(maxObject); // { a: 10, b: 7 }

Based on your code, after you found the index of the object with the highest summed values, you simply return the array in that index:

 var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; var max = [], maxIndex; var result; myArray.map(x => max.push(xa + xb)) maxIndex = max.indexOf(Math.max.apply(Math, max)) result = myArray[maxIndex]; console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM