# Find the closest number from an array

Return the item nearest to a target.

Canonical: https://1loc.dev/array/find-the-closest-number-from-an-array/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); }
```

## Input

```json
{
  "values": [
    29,
    87,
    8,
    78,
    97,
    20,
    75,
    33,
    24,
    17
  ],
  "target": 50
}
```

## Expected output

```json
33
```

## Edge case

Input:
```json
{
  "values": [
    10,
    20
  ],
  "target": 15
}
```
Output:
```json
10
```

## Limits

- The first candidate wins on ties, as the edge case shows. The lab requires at least one number.

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-closest-number-from-an-array.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: Takes values and target as one object; requires at least one number. Original MDX retained as inert source evidence.
