簡體   English   中英

JavaScript:從 Array 中找到總和值最高的 Object

[英]JavaScript: find Object with highest summed values from Array

需要來自 myArray 的具有最大 a+b 值的 Object

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

現在我有一些東西可以返回索引:

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

我需要返回 Object 而不是它的索引的東西,到目前為止正在使用

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

返回false

您可以使用如下所示的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)

希望這可以幫助。

不需要 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);

小提琴:返回最大的 object

你可以嘗試這樣的事情:

 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 }

根據您的代碼,在找到具有最高總和值的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM