Most frequent values
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 `k` values that appear most often in `items`, most frequent first. When two values appear equally often, the one that appeared first in `items` comes first. When there are fewer than `k` distinct values, return all of them; `k` of 0 returns `[]`. Values are strings or numbers and are told apart the way a `Map` tells keys apart, so `1` and `"1"` are different values. Do not change `items`.
What this exercise teaches
A Map counts without turning numbers into strings and remembers first appearance, and a stable sort by count alone keeps that order for ties. Breaking ties alphabetically, or counting with a plain object, changes the answer on the edge cases.
A hint if you get stuck
Count with a `Map` (it keeps insertion order, which is the first-appearance order). Turn it into entries, sort by count descending (sort is stable, so ties keep their order), and slice the first `k` keys.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Data shaping
- CSV text to objectsFree
- Totals per customerFree
- Pivot rows into a lookupFree
- Top N with tiesFree
- Running totalsFree
- Read a nested value by pathFree
- Deep equalityFree
- Flatten a nested objectFree
- Left join two listsFree
- Merge overlapping intervalsFree
- Deep cloneFree
- Unflatten dotted keysFree
- Flat list to a treeFree
- All orderings of a listFree