3

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]
    }
}

5 Answers5

4

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
eol
  • 23,236
  • 5
  • 46
  • 64
1

Sort the array in descending order and then get all 3 element by its index:

let numbers = new Array(6,34,6623,22,754,2677,12);
numbers.sort(function(a, b){return b-a});

console.log(numbers[0], numbers[1], numbers[2]);
Ankur Mishra
  • 1,284
  • 1
  • 6
  • 15
1

there is a simpler way you can achieve this. first, run a sort() on your array, then pick the highest ones.

const myArray = [7,4,99,10,55,1];
console.log(myArray.sort((a,b)=>b-a).slice(0, 3)) // [99, 55, 10]
Reza Shoja
  • 887
  • 2
  • 11
  • 24
1

Simply sort your array in descending order, then slice the first three values.

Note: .sort().reverse() is the speediest approach for sorting in descending order. See https://stackoverflow.com/a/52030227/129086

function getTopThree(arr) {
  // spread avoids modifying the original array
  return [...arr].sort().reverse().slice(0, 3);
}

getTopThree(numbers);

Whenever your numbers array is updated or changed, call getTopThree(numbers) again.

simmer
  • 2,639
  • 1
  • 18
  • 22
1

you can sort array

var numbers = [1,65,8,98,689,12,33,2,3,789];
var topValues = [... numbers].sort((a,b) => b-a).slice(0,3); 
Nonik
  • 645
  • 4
  • 11