Scriptdrill

Level 4: Data shaping Exercise 56 of 76 Free

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 exercise

More exercises in Data shaping