# Find the maximum item of an array by given key

Return the record with the largest value in a field.

Canonical: https://1loc.dev/array/find-the-maximum-item-of-an-array-by-given-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 maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); }
```

## Input

```json
{
  "values": [
    {
      "recipient": "ana@example.com",
      "attempts": 1
    },
    {
      "recipient": "rui@example.com",
      "attempts": 3
    }
  ],
  "key": "attempts"
}
```

## Expected output

```json
{
  "recipient": "rui@example.com",
  "attempts": 3
}
```

## Edge case

Input:
```json
{
  "values": [],
  "key": "attempts"
}
```
Output:
```json
null
```

## Limits

- An empty array returns null; the original returned {}.
- The first record wins on ties.

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/find-the-maximum-item-of-an-array-by-given-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: Returns null for an empty array instead of an empty object. Original MDX retained as inert source evidence.
