closest-to

A function that, when given a target number and an array of numbers, will return the array value closest to the target.

npm install closest-to
7 downloads in the last day
13 downloads in the last week
19 downloads in the last month

closest-to

closest-to is a function that, when given a target number and an array of numbers, will return the array value closest to the target.

Build status

Browser support

Install

npm install closest-to

Example

var closest = require('closest-to')

closest(10, [3, 7, 1, 9, 5])
// => 9

closest(-1.25, [2, 0, -1.5, -0.75])
// => -1.5

closest(5, [4, 6])
// => 4

// Works on multidimensional arrays as well
closest([1, 2], [[3, 4], [1, 1], [2, 3]])
// => [1, 1]

API

closest-to(

  target (number || array[number, …]) :
    any number

  numbers (array[number || array[number, …]) :
    the collection of numbers you 
    want to have searched 

)

Note

As you may have noticed in the example, if two numbers are equally close to the target, the first (lowest) number is returned. It would be trivial to instead return an array, but I don’t want to add code if it’s not necessary. If this behaviour is a problem for you, please post an issue.

License

MIT

npm loves you