Skip to content
UniCircle
EasyCodingArrays

Group an array of objects by a key

Question JS-COD-005

Implement groupBy(items, key): given an array of objects and a property name, return an object whose keys are the distinct values of that property and whose values are arrays of the matching objects.

  • Groups must appear in the order their key value is first seen.
  • Inside each group, objects keep their original order and are printed unchanged.

Constraints

  • At most 1000 objects; the input is at most 50000 characters.
  • Every object has the given property, and its value is a string of letters (never a number-like string).

Input and output

Input
Line 1: the property name Line 2: a JSON array of objects
Output
One line: the grouped object as compact JSON.

Examples

Input 1

branch
[{"name":"Asha","branch":"cse"},{"name":"Ravi","branch":"ece"},{"name":"Meena","branch":"cse"}]

Output

{"cse":[{"name":"Asha","branch":"cse"},{"name":"Meena","branch":"cse"}],"ece":[{"name":"Ravi","branch":"ece"}]}

Groups appear in order of first appearance; items keep their original order.

Input 2

city
[{"id":1,"city":"Pune"}]

Output

{"Pune":[{"id":1,"city":"Pune"}]}

One item, one group.

Show hints
  • reduce with an accumulator object is the classic answer.
  • Create the group array the first time you see a value.
Show the explanation

One pass with reduce: for each item, read item[key]; if the accumulator has no group for it yet, create an empty array; push the item.

JavaScript
const grouped = items.reduce((acc, item) => {
  (acc[item[key]] ??= []).push(item);
  return acc;
}, {});

String keys keep insertion order in JavaScript objects, which gives "first seen" order for free. (Integer-like keys such as "2" would be moved to the front, which is why the constraints exclude them; a Map avoids the issue.) Modern runtimes also provide Object.groupBy(items, fn), which does the same thing.

Original UniCircle question. Last reviewed 22 Oct 2026.