簡體   English   中英

在 json object 和 javascript 和相應的索引或其他值中查找最大數字

[英]Find the highest number in a json object with javascript and a corresponding index or another value

這個 javascript 找到最高的數字,但我也想要相應的 id 和索引,或相應的 id。

const shots = [{
    id: 1,
    amount: 2
  },
  {
    id: 2,
    amount: 4
  },
  {
    id: 3,
    amount: 52
  },
  {
    id: 4,
    amount: 36
  },
  {
    id: 5,
    amount: 13
  },
  {
    id: 6,
    amount: 33
  }
];

var highest = shots.reduce((acc, shot) => acc = acc > shot.amount ? acc : shot.amount, 0);

或者

var highest = Math.max.apply(Math, shots.map(function(o) { return o.amount; }))

在這個例子中,最大的數字是 52 則表示對應的索引是 2。如何獲得這個索引值?

最后,我需要得到相應的id。

在現實生活中,我應該找到最高的比特率來獲得相應的最高質量的視頻 url。

一旦您擁有最高金額,您可以.findIndex以獲取具有該金額的 object。

 const shots=[{id:1,amount:2},{id:2,amount:4},{id:3,amount:52},{id:4,amount:36},{id:5,amount:13},{id:6,amount:33}]; const highest = Math.max(...shots.map(o => o.amount)); const index = shots.findIndex(o => o.amount === highest); console.log(index, shots[index].id);

或者,如果您只想通過一次迭代來完成它

 const shots=[{id:1,amount:2},{id:2,amount:4},{id:3,amount:52},{id:4,amount:36},{id:5,amount:13},{id:6,amount:33}]; let index = 0; let best = -Infinity; shots.forEach((shot, i) => { if (shot.amount > best) { best = shot.amount; index = i; } }); console.log(index, shots[index].id);

如果只希望索引獲取到ID,那就簡單一些了。

 const shots=[{id:1,amount:2},{id:2,amount:4},{id:3,amount:52},{id:4,amount:36},{id:5,amount:13},{id:6,amount:33}]; const best = shots.reduce((a, b) => a.amount > b.amount? a: b); console.log(best);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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