Home > Enterprise >  Find the highest number in a json object with javascript and a corresponding index or another value
Find the highest number in a json object with javascript and a corresponding index or another value

Time:08-10

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.

CodePudding user response:

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

  • Related