Skip to content

#187 Largest Numbers

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

187 Largest Numbers

Create a function that takes two arguments of an array of numbers arr and a constant number n and returns the n largest numbers from the given array.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/187 Largest Numbers.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

//Create a function that takes two arguments of an array of numbers arr and a constant number n and returns the n largest numbers from the given array.
function largestNumbers(n, arr) {
    n = Math.floor(n);                // optional: ensure integer
    if (n <= 0) return [];
    const sorted = arr.slice().sort((a, b) => a - b);
    return n >= sorted.length ? sorted.slice() : sorted.slice(-n);
}
import { assertEquals } from '../testHelper.js';
assertEquals(largestNumbers(2, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), [9, 10])
assertEquals(largestNumbers(3, [5, 1, 5, 2, 3, 1, 2, 3, 5]), [5, 5, 5])
assertEquals(largestNumbers(7, [9, 1, 50, 22, 3, 13, 2, 63, 5]), [3, 5, 9, 13, 22, 50, 63])
assertEquals(largestNumbers(0, [1, 2, 3, 4, 8, 7, 6, 5]), [])
assertEquals(largestNumbers(2, [4, 3, 2, 1]), [3, 4])
assertEquals(largestNumbers(1, [7, 19, 4, 2]), [19])
assertEquals(largestNumbers(3, [14, 12, 57, 11, 18, 16]), [16, 18, 57])

Clone this wiki locally