[英]JavaScript: find Object with highest summed values from Array
In need the Object with maximum a+b value from myArray需要来自 myArray 的具有最大 a+b 值的 Object
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我需要返回 Object 而不是它的索引的东西,到目前为止正在使用
var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y)
returning false
.返回false
。
You can use reduce
like below您可以使用如下所示的reduce
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.不需要 map 因为 reduce 会遍历你的数组。
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小提琴:返回最大的 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:根据您的代码,在找到具有最高总和值的 object 的索引后,您只需返回该索引中的数组:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.