1

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.

4
  • 1
    If you can get the index then you can get the object with myArray[maxIndex] Commented Jul 1, 2020 at 10:49
  • true, I wanted something more efficient and shorter if possible, not understanding much of the Array.reduce yet. Commented Jul 1, 2020 at 10:51
  • 1
    myArray.reduce((x,y) => x.a + x.b > y.a + y.b ? x : y) – you need to return x or y and not the boolean from the comparison, and if you reduce the array of sums you get the highest sum and not the object. Commented Jul 1, 2020 at 10:57
  • Thank you, this is what I was looking for. Commented Jul 1, 2020 at 11:03

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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 }

Comments

0

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(x.a + x.b))
maxIndex = max.indexOf(Math.max.apply(Math, max))
result = myArray[maxIndex];
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.