Scriptdrill

Level 2: Arrays and objects Exercise 11 of 45 Pro

Count by a field

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return an object that maps each value of `item[key]` to how many items have it. Skip items where the field is missing or `undefined`.

What this exercise teaches

`(counts[k] || 0) + 1` starts a new count at 1 and increases existing ones. Skipping undefined keeps a stray "undefined" key out of the result.

A hint if you get stuck

Loop once. For each item read `item[key]`, skip `undefined`, and add 1 to the count, starting from 0 the first time.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Arrays and objects