Count how often each value appears
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 aMap.
Stuck? The javascript course covers everything this challenge needs.
- 1.counts repeated strings
- 2.returns an empty object for an empty array
- 3.counts numbers using their string form as the key
- 4.counts booleans
- 5.does not mutate the input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.