Get the max n values from an array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n, as the second argument.

Our function should then pick the n greatest numbers from the array and return a new array consisting of those numbers.

Using Sort and Slice

The most straightforward approach is to sort the array in descending order and take the first n elements:

const arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52];

const pickGreatest = (arr = [], num = 1) => {
    if(num > arr.length){
        return [];
    }
    const sorter = (a, b) => b - a;
    const descendingCopy = arr.slice().sort(sorter);
    return descendingCopy.slice(0, num);
};

console.log(pickGreatest(arr, 3));
console.log(pickGreatest(arr, 4));
console.log(pickGreatest(arr, 5));
[ 52, 30, 22 ]
[ 52, 30, 22, 20 ]
[ 52, 30, 22, 20, 18 ]

Alternative: Using Math.max() with Loop

For smaller arrays or when you need to preserve original order of max values:

const arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52];

const getMaxN = (arr, n) => {
    if (n > arr.length) return [];
    
    const result = [];
    const tempArr = [...arr];
    
    for (let i = 0; i < n; i++) {
        const maxValue = Math.max(...tempArr);
        result.push(maxValue);
        const index = tempArr.indexOf(maxValue);
        tempArr.splice(index, 1);
    }
    
    return result;
};

console.log(getMaxN(arr, 3));
[ 52, 30, 22 ]

Performance Comparison

Method Time Complexity Space Complexity Best For
Sort + Slice O(n log n) O(n) Medium to large arrays
Math.max() Loop O(n × k) O(n) Small arrays or small k values

Edge Cases

const testArray = [1, 2, 3];

console.log(pickGreatest([], 2));      // Empty array
console.log(pickGreatest(testArray, 0)); // Zero elements
console.log(pickGreatest(testArray, 5)); // More than array length
[]
[]
[]

Conclusion

The sort-based approach is generally preferred for its simplicity and consistent O(n log n) performance. Use the Math.max() method when you need to maintain the original relative order of maximum values.

Updated on: 2026-03-15T23:19:00+05:30

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements