Find the closest number from an array
Return the item nearest to a target.
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
33The edge case
Input
{
"values": [
10,
20
],
"target": 15
}Expected output
10Know 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.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.