dev
dev

Reputation: 41

How to find three largest numbers in an array?

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

Upvotes: 0

Views: 1307

Answers (1)

DecPK
DecPK

Reputation: 25408

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

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

Upvotes: 2

Related Questions