Home > other >  How to find three largest numbers in an array?
How to find three largest numbers in an array?

Time:11-24

Hello I want to find the three largest numbers in an array by ORDER. I am confused how I should implement the last logic where I have to shift the indexes of the result array based on if the the current number in the result array is greater or less than the loop of the array items.

    function findThreeLargestNumbers(array) {
  let result = [null, null, null];
  for (let i = 0; i < array.length; i  ) {
    if (!result[2] || result[i] > result[2]) {
      for (let j = 0; i <= 2; i  ) {
        if (j === 2) {
          result[j] = array[i]
        } else {
          result[j] = array[i   1]
        }
      }
    }
  }
  return result
}


console.log(findThreeLargestNumbers([141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7]));

CodePudding user response:

You can simply sort it in ascending order and use slice to get the last 3 elements as:

1) When you want result in last 3 largest in ascending order [18, 141, 541]

function findThreeLargestNumbers(array) {
  return [...array].sort((a, b) => a - b).slice(-3);
}

// [18, 141, 541]
console.log(findThreeLargestNumbers([141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) When you want result in last 3 largest in descending order [541, 141, 18]

function findThreeLargestNumbers(array) {
  return [...array].sort((a, b) => b - a).slice(0, 3);
}

console.log(findThreeLargestNumbers([141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related