Last updated: December 2, 2026.
Sort a copy in descending numeric order and take the first n elements. This preserves the input array and lets you decide whether equal values count as separate results.
function largestNumbers(values, n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError('n must be a nonnegative integer');
}
if (!values.every(Number.isFinite)) {
throw new TypeError('Expected finite numbers');
}
return values.toSorted((a, b) => b - a).slice(0, n);
}
const scores = [18, 4, 71, 25, 71];
console.log(largestNumbers(scores, 3)); // [71, 71, 25]Choose how to handle ties
The example expects a dense array of numbers. The comparator passes a negative result to the sorting algorithm when the larger value belongs first. A default sort compares string representations, which can put 100 before 9 in ascending order. A numeric comparator prevents that surprise.
The result contains at most n elements. A count of zero gives an empty array. A count greater than the length gives every element in descending order. Equal values occupy separate positions. If you need distinct values, remove duplicates first with [...new Set(scores)] and pass that array to the function.
Keep the original array and validate the input
toSorted() returns a new array. In a runtime without it, make a copy with slice() and call sort() on that copy. For values from a form or API, normalize and validate them before sorting. For example, a string containing only whitespace should be rejected before number conversion if an empty field would otherwise become zero.
Sorting the entire array is easy to review for ordinary lists. If you process a large stream and only need a few results, keeping a fixed-size heap can reduce memory use. Before optimizing, test a tie, a negative value, and a count larger than the input.