简体   繁体   English

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

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

This javascript find the highest number but i want the corresponding id and index too, or the corresponding id.这个 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);

OR或者

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

In this example the highest number is 52 then it mean that the corresponding index is 2. how to get this index value?在这个例子中,最大的数字是 52 则表示对应的索引是 2。如何获得这个索引值?

Finally, i need to get the corresponding id.最后,我需要得到相应的id。

In real life, i should find the highest bitrate to get the corresponding highest quality video url.在现实生活中,我应该找到最高的比特率来获得相应的最高质量的视频 url。

Once you have the highest amount, you can .findIndex to get the object with that amount.一旦您拥有最高金额,您可以.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);

Or if you wanted to do it with just a single iteration或者,如果您只想通过一次迭代来完成它

 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);

If you only want the index to get to the ID, it's a bit easier.如果只希望索引获取到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