Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the highest 3 values from a json file

So I need to get the highest 3 values from an array, though I don't know how many values I need to check since that number will change periodically, I tried running this loop but it doesn't work.

numbers = new array();
numbers = (6,34,6623,22,754,2677,12)
var num1 = 0
var num2 = 0
var num3 = 0
for (var i=0; i<numbers.length;i++) {
    if num1<numbers[i] {
        num1 = numbers[i]
    } else if num2<numbers[i] {
         num2 = numbers[i]
      } else if num3<numbers[i] {
           num3 = numbers[i]
    }
}
like image 561
MagicHappened Avatar asked Jan 31 '26 05:01

MagicHappened


1 Answers

All of the other answers propose the correct and fast way to do this, i.e. to sort the array in descending order and take the first three elements.

If you're interested why your code did not work: The problem is that you need to keep track of each of the last found max values if a new one is found. You need to change your code to something like this:

const numbers = [6, 34, 6623, 22, 754, 2677, 12]
let max = 0;
let oneLowerToMax = 0;
let twoLowerToMax = 0;
for (let i = 0; i < numbers.length; i++) {
   if (numbers[i] > max) {
       twoLowerToMax = oneLowerToMax;
       oneLowerToMax = max;
       max = numbers[i];
   }else if(numbers[i] > oneLowerToMax) {
       twoLowerToMax = oneLowerToMax;
       oneLowerToMax = numbers[i];
   }else if(numbers[i] > twoLowerToMax) {
       twoLowerToMax = numbers[i];
   }
}

console.log(max, oneLowerToMax, twoLowerToMax) // prints 6623, 2677, 754
like image 143
eol Avatar answered Feb 02 '26 17:02

eol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!