Code Lab

Timer: 12 min, like in an interview. Hints and autocomplete are off while it runs

Group by a key

MediumObjects12 min

Write a function groupBy(items, key) that puts the items of an array into groups and returns an object: group name to the array of its items.

  • items is an array of objects, for example test results { name: 'login', status: 'pass' }. It can be empty: then return {}.
  • key is either the name of a field, such as 'status', or a function that gets an item and returns its group name, such as (r) => r.ms > 1000 ? 'slow' : 'fast'.
  • The group name is the value of that field (or what the function returns). Object keys are strings, so a field value 200 gives the group '200'.
  • Inside a group the items keep their order from items.
  • Put the items themselves into the groups, not copies. Do not change items.
  • Do not use Object.groupBy or Map.groupBy: write the loop. A hidden test makes them throw an error.

Examples

groupBy([{ name: 'login', status: 'pass' }, { name: 'cart', status: 'fail' }, { name: 'search', status: 'pass' }], 'status')

Returns { pass: [ { name: 'login', status: 'pass' }, { name: 'search', status: 'pass' } ], fail: [ { name: 'cart', status: 'fail' } ] }

groupBy([{ code: 200 }, { code: 404 }, { code: 200 }], 'code')

Returns { '200': [ { code: 200 }, { code: 200 } ], '404': [ { code: 404 } ] }

groupBy([], 'status')

Returns {}

Source

Loading the editor...
  1. InputgroupBy([ { name: 'login', status: 'pass' }, { name: 'cart', status: 'fail' }, { name: 'search', status: 'pass' } ], 'status')
    Expected{ pass: [ { name: 'login', status: 'pass' }, { name: 'search', status: 'pass' } ], fail: [ { name: 'cart', status: 'fail' } ] }
  2. InputgroupBy([ { code: 200 }, { code: 404 }, { code: 200 } ], 'code')
    Expected{ '200': [ { code: 200 }, { code: 200 } ], '404': [ { code: 404 } ] }
  3. InputgroupBy([], 'status')
    Expected{}

Hidden tests run on Submit