# Coding Challenge - #33: Group By Key

**URL:** <https://forum.kirupa.com/t/coding-challenge-33-group-by-key/683770>\
**Category:** web dev\
**Created:** [October 17, 2026, 10:00pm UTC](https://forum.kirupa.com/t/coding-challenge-33-group-by-key/683770 "2026-10-17T22:00:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ArthurDent](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/arthurdent/32/31262_2.png) [@ArthurDent](https://forum.kirupa.com/u/ArthurDent)\
**Post date:** [October 17, 2026, 10:00pm UTC](https://forum.kirupa.com/t/coding-challenge-33-group-by-key/683770/1 "2026-10-17T22:00:04Z")

</div>

Write `groupBy(items, key)` that returns an object grouping the array of objects by the given property. `groupBy([{t:"a",v:1},{t:"b",v:2},{t:"a",v:3}], "t")` should give `{a:[{t:"a",v:1},{t:"a",v:3}], b:[{t:"b",v:2}]}`.

```js
function groupBy(items, key) {
  // your code here
}

```

**Rules:**

- Plain JavaScript, no libraries
- Do not mutate the input array

Post your solution as a reply. Answer goes up in about a day.

---

<div class="post-metadata">

**Author:** ![Apexcodes](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/apexcodes/32/33967_2.png) [@Apexcodes](https://forum.kirupa.com/u/Apexcodes)\
**Post date:** [October 18, 2026, 3:21am UTC](https://forum.kirupa.com/t/coding-challenge-33-group-by-key/683770/2 "2026-10-18T03:21:11Z")

</div>

You can use `reduce()` to group the items by the selected property without modifying the original array:

```auto
function groupBy(items, key) {
  return items.reduce((groups, item) => {
    const value = item[key];

    if (!Object.hasOwn(groups, value)) {
      groups[value] = [];
    }

    groups[value].push(item);
    return groups;
  }, {});
}

```

This keeps the original order of items within each group and runs in O(n) time on average. `Object.hasOwn()` also avoids treating inherited object properties as existing groups.
