How to find the two largest elements in an array with JavaScript

1 Answer

0 votes
/**
 * Finds the largest and second-largest elements in an array.
 *
 * @param {number[]} numbers - Input array of numbers.
 * @returns {{ largest: number, secondLargest: number }}
 * @throws {Error} If the array contains fewer than two elements.
 */
function findTwoLargest(numbers) {
    if (numbers.length < 2) {
        throw new Error("Array must contain at least two elements.");
    }

    let largest = Number.NEGATIVE_INFINITY;
    let secondLargest = Number.NEGATIVE_INFINITY;

    for (const value of numbers) {
        // Found a new largest value
        if (value > largest) {
            secondLargest = largest;
            largest = value;
        }
        // Update second largest if needed
        else if (value > secondLargest) {
            secondLargest = value;
        }
    }

    return {
        largest,
        secondLargest
    };
}

// Input data
const numbers = [3, 4, 9, 6, 7, 1, 2, 5];

// Find the two largest elements
const { largest, secondLargest } = findTwoLargest(numbers);

// Display results
console.log("Array:", numbers);
console.log("Largest element:", largest);
console.log("Second largest element:", secondLargest);


/*
run:

Array: [
  3, 4, 9, 6,
  7, 1, 2, 5
]
Largest element: 9
Second largest element: 7

*/

 



answered 15 hours ago by avibootz
...