typestar

Count by key in JavaScript

Tallies how many items fall under each computed key.

function countBy(items, keyFn) {
  const counts = {};
  for (const item of items) {
    const key = keyFn(item);
    counts[key] = (counts[key] || 0) + 1;
  }
  return counts;
}

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
161
Tokens
51
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 32 seconds.

Type this snippet

Step 6 of 8 in Objects & collections, step 32 of 43 in Language basics.

← Previous Next →