Count items by a computed key
Filter sidebars show counts: "Open (12)", "Closed (3)". Those numbers come from tallying a list by some derived property rather than storing them separately.
Implement countBy(items, keyFn). For each item, call keyFn(item) to get its bucket, then return a plain object mapping each bucket to the number of items in it. Because these are object properties, the returned keys are strings: a keyFn returning the number 1 produces the key "1", and one returning true produces "true". Buckets with no items never appear. An empty input array returns an empty object.
Arguments
itemsArray- The input list to tally.
keyFn(item) => any- Called with each item to pick its bucket. Return value is coerced to a string.
Returns
Object<string, number> — A plain object mapping each key keyFn produces to the number of items in that bucket.
Examples
countBy(["apple", "banana", "avocado"], (word) => word[0]);
// { a: 2, b: 1 }countBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? "even" : "odd"));
// { odd: 3, even: 2 }
countBy([true, false, true], (flag) => flag);
// { true: 2, false: 1 } — boolean keys become stringsWhat it has to do
- Return a plain object mapping each key produced by
keyFnto its count. - Keys are the string form of whatever
keyFnreturns, so numbers and booleans become strings. - Only keys that actually occur appear in the result.
- Return
{}for an empty input array.
Stuck? The javascript course covers everything this challenge needs.
- 1.tallies by the returned key
- 2.handles a two-bucket predicate key
- 3.returns an empty object for empty input
- 4.stringifies numeric keys
- 5.stringifies boolean keys
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.