Scriptdrill

Level 4: Data shaping Exercise 31 of 45 Pro

Top N with ties

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return the `n` items with the highest `item[key]`, highest first. If more items tie with the value of the `n`th one, include them all. Items with equal values keep their original order. `n` can be 0 or larger than the list. Do not change `items`.

What this exercise teaches

A stable sort from high to low puts tied items next to each other in their original order. Keeping everything up to the nth position plus anything equal to the nth value adds the ties without a second sort.

A hint if you get stuck

Sort a copy from high to low. If there are more than `n` items, note the value at position `n - 1` and keep every item before it plus every item equal to it.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Data shaping