# Group objects by a key

Collect records by a string or numeric field without prototype-key collisions.

Canonical: https://1loc.dev/array/group-an-array-of-objects-by-a-key/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function groupBy({ values, key }) { const groups = new Map(); for (const value of values) { const group = String(value[key]); groups.set(group, [...(groups.get(group) || []), value]); } return Object.fromEntries(groups); }
```

## Input

```json
{
  "values": [
    {
      "recipient": "ana@example.com",
      "status": "delivered"
    },
    {
      "recipient": "rui@example.com",
      "status": "deferred"
    },
    {
      "recipient": "lia@example.com",
      "status": "delivered"
    }
  ],
  "key": "status"
}
```

## Expected output

```json
{
  "delivered": [
    {
      "recipient": "ana@example.com",
      "status": "delivered"
    },
    {
      "recipient": "lia@example.com",
      "status": "delivered"
    }
  ],
  "deferred": [
    {
      "recipient": "rui@example.com",
      "status": "deferred"
    }
  ]
}
```

## Edge case

Input:
```json
{
  "values": [
    {
      "team": "__proto__"
    }
  ],
  "key": "team"
}
```
Output:
```json
{
  "__proto__": [
    {
      "team": "__proto__"
    }
  ]
}
```

## Limits

- Every record must own the grouping field, with a string or number value.
- Group keys become strings, so numeric 1 and string "1" share a group.

The lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/group-an-array-of-objects-by-a-key.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Curated implementation; explicit input bounds, edge cases, local fixtures and rebuilt presentation. Original MDX retained as inert source evidence.
