AniUI Academy

Count how often each value appears

easyData Structures+150 XPPractice

Filter sidebars show a count next to every option, dashboards show how many events of each type arrived, and a tag cloud sizes each tag by its tally. All of it is the same one-pass count.

Implement countFrequencies(items). items is an array of primitive values (strings, numbers or booleans). Return a plain object whose keys are the string form of each distinct value and whose values are how many times that value appeared. An empty array returns an empty object. Do not modify the input array.

Arguments

itemsArray<string | number | boolean>
An array of primitive values to tally.

Returns

Record<string, number> — An object mapping the string form of each distinct value to how many times it appeared.

Examples

countFrequencies(["a", "b", "a", "c", "a"]);
// { a: 3, b: 1, c: 1 }
countFrequencies([1, 2, 2, 3, 3, 3]);
// { "1": 1, "2": 2, "3": 3 }

Numeric values are coerced to string keys, as object keys always are.

countFrequencies([]);
// {}

What it has to do

  • Return a plain object mapping the string form of each value to its count.
  • Return an empty object for an empty array.
  • Count numbers and booleans as well as strings.
  • Do not mutate the input array.

Notes

  • A single O(n) pass over the array; each key lookup and update is O(1).
  • Because object keys are strings, countFrequencies([1, '1']) would collapse to { '1': 2 }. If you need to preserve the type distinction, reach for a Map.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.