0

This javascript find the highest number but i want the corresponding id and index too, or the corresponding id. This is not a duplicate question since i'm looking for the id or the index and not just finding the highest number.

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?

Finally, i need to get the corresponding id.

In real life, i should find the highest bitrate to get the corresponding highest quality video url.

Gino
  • 1,834
  • 2
  • 19
  • 20
  • Does this answer your question? [Finding the max value of an attribute in an array of objects](https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects) The second (not accepted) [answer](https://stackoverflow.com/a/34087850/2610061) there is exactly what is needed in this case. – Carsten Massmann Aug 09 '22 at 05:16
  • Check this https://codepen.io/Maniraj_Murugan/pen/ZExRPbp – Maniraj Murugan Aug 09 '22 at 05:23
  • I need the corresponding id or index. and the other question do not provide that. Maniraj. it look like what i need thank's. – Gino Aug 09 '22 at 06:14

1 Answers1

1

Once you have the highest amount, you can .findIndex to get the object with that amount.

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.

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320