AniUI Academy

Count items by a computed key

easyArrays & Objects+150 XPPractice

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 strings

What it has to do

  • Return a plain object mapping each key produced by keyFn to its count.
  • Keys are the string form of whatever keyFn returns, 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.

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.