Reputation: 4479
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
.
Upvotes: 1
Views: 355
Reputation: 68
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
Upvotes: 1
Reputation: 388
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);
Upvotes: 0
Reputation: 363
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 }
Upvotes: 0
Reputation: 6009
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.
Upvotes: 2