EasyPythonJavaScriptTypeScript

Group By

ArraysObjectsFunctions

Implement solve(arr, key) that groups an array of objects by a given
property name and returns a plain object where each property maps to the
sub-array of matching items.

Example

solve([
  { name: 'Alice', dept: 'eng' },
  { name: 'Bob',   dept: 'hr'  },
  { name: 'Carol', dept: 'eng' },
], 'dept')
// → { eng: [{name:'Alice',dept:'eng'},{name:'Carol',dept:'eng'}], hr: [{name:'Bob',dept:'hr'}] }

Constraints

  • Preserve the relative order within each group.
  • The result must only contain keys that appear in the input.

Sample tests

Test #1Single element
Input: [[{"k":"a","v":1}],"k"]
Output: {"a":[{"k":"a","v":1}]}
Test #2Two groups
Input: [[{"t":"a","v":1},{"t":"b","v":2},{"t":"a","v":3}],"t"]
Output: {"a":[{"t":"a","v":1},{"t":"a","v":3}],"b":[{"t":"b","v":2}]}
Test #3All items in one group
Input: [[{"g":1,"n":"a"},{"g":1,"n":"b"},{"g":1,"n":"c"}],"g"]
Output: {"1":[{"g":1,"n":"a"},{"g":1,"n":"b"},{"g":1,"n":"c"}]}
Test #4Three distinct groups
Input: [[{"id":1,"type":"x"},{"id":2,"type":"y"},{"id":3,"type":"x"},{"id":4,"type":"z"}],"type"]
Output: {"x":[{"id":1,"type":"x"},{"id":3,"type":"x"}],"y":[{"id":2,"type":"y"}],"z":[{"id":4,"type":"z"}]}
Test #5Empty array → empty object
Input: [[],"x"]
Output: {}