Return Top two elements from array JavaScript

We have an array of numbers in JavaScript that contains numbers in an unsorted order. Our job is to write a function that takes in this array of numbers and returns an array of two elements, the top two elements of the array (greatest two elements of the array).

We have to do this in one pass i.e., we need to execute this method in linear time like by using only one for loop or if we use ES6 function, we have to make sure to use only one and once and avoid nesting of methods which increases time complexity.

Using Array.prototype.reduce() Method

The reduce() method allows us to traverse the array once while maintaining the two largest values:

const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3];

const topTwo = arr => {
    if(arr.length < 2){
        return false;
    };
    return arr.reduce((acc, val) => {
        if(val > acc[0]){
            let t = acc[0];
            acc[0] = val;
            acc[1] = t;
        }else if(val > acc[1]){
            acc[1] = val;
        };
        return acc;
    }, [-Infinity, -Infinity]);
};

console.log(topTwo(arr));
[ 234, 87 ]

How It Works

The algorithm maintains two variables in the accumulator array:

  • acc[0] - stores the largest element found so far
  • acc[1] - stores the second largest element

For each element, we check if it's larger than the current largest. If so, we shift the current largest to second position and update the largest. If it's only larger than the second largest, we update just the second position.

Alternative: Using a Simple Loop

const findTopTwo = (arr) => {
    if (arr.length < 2) return false;
    
    let first = -Infinity;
    let second = -Infinity;
    
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] !== first) {
            second = arr[i];
        }
    }
    
    return [first, second];
};

const numbers = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3];
console.log(findTopTwo(numbers));
[ 234, 87 ]

Key Points

  • Both approaches have O(n) time complexity - single pass through the array
  • Space complexity is O(1) - only using constant extra space
  • Handle edge cases like arrays with fewer than 2 elements
  • The loop version also checks for duplicates of the largest number

Conclusion

Both the reduce() method and simple loop approach efficiently find the top two elements in linear time. Choose based on your preference for functional vs imperative programming style.

Updated on: 2026-03-15T23:18:59+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements