Find the closest number from an array

Return the item nearest to a target.

JavaScript Version 1.0.0 · MIT · .md

find-the-closest-number-from-an-array.js
function closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); }

Input & expected output

Input

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

Expected output

33

The edge case

Input

{
  "values": [
    10,
    20
  ],
  "target": 15
}

Expected output

10

Know the limits

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

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Find the closest number from an array from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Takes values and target as one object; requires at least one number. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.