[Question]
  [
In this code golf, you need to get the closest number from another one in a list.
The output may be the closest number to the input.
Example:
```
value: (Input) 5 --- [1,2,3] --- 3
```
And, the program may work with negative numbers.
Example:
```
value: (Input) 0 --- [-1,3,5] --- -1
value: (Input) 2 --- [1, 5, 3] --- 1 (Because it gives priority to lower numbers)
```
**RULES:**
As mentioned before, it has to work with negative numbers.
If there are two answers (Example: 0 -- [5,-5]), the program gives priority to the lowest number. (-5)
This is code golf so the shortest code wins!
  
[Answer]
# Pyth, 6 bytes
```
haDQSE
```
[Test suite](https://pyth.herokuapp.com/?code=haDQSE&test_suite=1&test_suite_input=5%0A1%2C2%2C3%0A0%0A-1%2C3%2C5%0A2%0A1%2C5%2C3%0A4%0A1%2C5%2C3&debug=0&input_size=2)
Input in the following form on STDIN:
```
num
array
```
Explanation:
```
haDQSE
          Implicit: Q = eval(input()) (num)
     E    Evaluate input (array)
    S     Sort (smaller values to the front)
 aDQ      Sort by absolute difference with Q.
h         Take the first element of the sorted list, the min.
          Print implicitly.
```
[Answer]
## Ruby, 34 bytes
```
->n,a{a.sort.min_by{|x|(n-x).abs}}
```
```
a.sort       min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x|  select the element which returns the smallest val for predicate...
(n-x).abs}   (absolute) difference between input num and element
```
[Answer]
# Mathematica, 12 bytes
```
Min@*Nearest
```
Built-ins FTW! Buettner's explanation: "Mathematica has a built-in `Nearest` for this, but it returns a list of all tied numbers. Hence, we need to compose it with `Min` to break the tie."
[Answer]
# Pyth, 8 bytes
```
hS.mabQE
```
Explanation
```
         - autoassign Q = eval(input())
  .m   E -   min_values([V for b in eval(input())])
    abQ  -    abs(b-Q)
 S       -  sorted(^)
h        - ^[0]
```
[Try it online!](http://pyth.herokuapp.com/?code=hS.mabQE&input=2%0A%5B3%2C+1%5D&debug=0)
[Answer]
## JavaScript ES6, ~~64~~ ~~56~~ 54 bytes
```
(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]
```
[Try it online](http://vihan.org/p/esfiddle/?code=f%3D(i%2Ca)%3D%3Ea.sort((a%2Cb)%3D%3Es(i-a)-s(i-b)%7C%7Ca-b%2Cs%3DMath.abs)%5B0%5D%0A%0Af(2%2C%20%5B1%2C5%2C3%5D))
Thanks to [@Niel](https://codegolf.stackexchange.com/users/17602/neil) for saving two bytes
Test Snippet:
```
f=(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0];
[
  [5, [1, 2, 3]],
  [2, [3, 5, 1]],
  [2, [1, 3, 5]],
  [0, [-1, 2, 3]],
  [5, [1, 2, 3]]
].map(v=>O.textContent+=JSON.stringify(v)+": "+f.apply(null,v)+"\n")
```
```
<pre id=O></pre>
```
[Answer]
# Jelly, ~~7~~ 6 bytes
```
ạżṛỤḢị
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqhxbzhuZvhu6ThuKLhu4s&input=&args=Mg+WzEsIDUsIDNd)
### How it works
```
ạżṛỤḢị Main link. Left input: n (number). Right input: A (list)
ạ      Take the asbolute difference of n and the items of A.
  ṛ    Yield the right argument, A.
 ż     Zip the left result with the right one.
       This pairing causes ties in absolute value to be broken by initial value.
   Ụ   Grade up; sort the indices of the resulting list by their associated values.
    Ḣ  Retrieve the first index, which corresponds to the smallest value.
     ị Retrieve the item of A at that index.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ạÐṂṂ
```
[Try it online!](https://tio.run/##y0rNyan8///hroWHJzzc2QRE/w8vV/r/P9pQx0jHOFZHIVrXUMdYxxTEMtQxhQjBGaY6uqax/011FAx0FIx0FHQNjYyBbAA "Jelly – Try It Online")
This takes `A` on the left and `n` on the right
I'm guessing the `ÐṂ` builtin didn't exist when Dennis wrote [his answer](https://codegolf.stackexchange.com/a/72062/66833).
## How it works
```
ạÐṂṂ - Main link. Takes A on the left and n on the right
 ÐṂ  - Keep elements of A with a minimal:
ạ    -   Absolute difference with n
   Ṃ - Take the minimum
```
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
(x=scan())[order(abs(x-scan()),x)][1]
```
[Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DUzM6vygltUgjMalYo0IXKqZToRkbbRj731TBWMGQi8uI6z8A "R – Try It Online")
After 4 years, 5 bytes shorter than [the previous R answer](https://codegolf.stackexchange.com/a/73105/95126).
Uses the `order()` function with two arguments, to order first by the closeness to the target value, and then to break ties by the array value. Finally outputs the first element after re-ordering.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~17~~ 16 [bytes](https://github.com/abrudz/SBCS)
```
⊢{⌊/⍺/⍨⍵=⌊/⍵}∘|-
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXoupHPV36j3p3AfGKR71bbSHcrbWPOmbU6P5Pe9Q24VFv36Ou5ke9ax71bjm03vhR28RHfVODg5yBZIiHZ/B/U4U0BUMFIwVjLgMg69B6QwVjBVMuI7CoKVAUxAKKKBgCAA "APL (Dyalog Unicode) – Try It Online")
This is a function which takes a single number as a left argument and a list of numbers as a right argument.
The general structure of this is a fork consisting of:
* the constant right function `⊢` returns the list of numbers
* `|-` calculates the absolute value of each difference between a number from the list and the left argument
* and the dfn `{⌊/⍺/⍨⍵=⌊/⍵}` which is called with the results of the other two functions:
```
            ⍝ ⍵: absolute differences (|-)
            ⍝ ⍺: the original list (⊢)
       ⌊/⍵  ⍝ the minimum of the absolute differences
     ⍵=     ⍝ element-wise equal to the absolute differences
  ⍺/⍨       ⍝ select all values from the original list where this is 1
⌊/          ⍝ take the minimum
```
A fully tacit function came out at 17 bytes: [`⌊/∘∊((⊢=⌊/)∘|-)⊆⊢`](https://tio.run/##SyzI0U2pTMzJT////1FPl/6jjhmPOro0NB51LbIF8TWBAjW6mo@62oAi/9MetU141Nv3qKv5Ue@aR71bDq03ftQ28VHf1OAgZyAZ4uEZ/N9UIU3BUMFIwZjLAMg6tN5QwVjBlMsILGoKFAWxgCIKhgA).
---
With some help from [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m), here is a shorter function in the extended variant:
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
```
(⊃⍋⍤|⍤-⊇⊢)∘∧
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRV/Oj3u5HvUtqgFj3UVf7o65Fmo86ZjzqWP4/7VHbhEe9fWAlax71bjm03vhR28RHfVODg5yBZIiHZ/B/U4U0BUMFIwVjLgMg69B6QwVjBVMuI7CoKVAUxAKKKBiC5Y2BKg0B "APL (Dyalog Extended) – Try It Online")
Same arguments as before, `∧` sorts the list ascending and `⊃⍋⍤|⍤-⊇⊢` is applied with the left number and the sorted list as a right argument.
```
     -   ⍝ the difference between the left argument and each list entry of the sorted list
   |     ⍝ take the absolute values
 ⍋       ⍝ the indices that would sort this list (stable)
      ⊇  ⍝ index with these indices into ...
       ⊢ ⍝ ... the sorted list. This resorts the list on the absolute difference
⊃        ⍝ pick the first value
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
Sti-|4#X<)
```
[**Try it online!**](http://matl.tryitonline.net/#code=U3RpLXw0I1g8KQ&input=WzUgLTVdCjA)
```
S       % implicitly input array, and sort. This ensures smaller numbers have priority
t       % duplicate
i       % input number
-|      % compute array of absolute differences
4#X<    % arg min. If there are several minimizers, the position of the first is returned
)       % index into original array. Implicitly display
```
[Answer]
## Python 2, 56 bytes
```
a=input()
print sorted(input(),key=lambda x:abs(a-x))[0]
```
Gets the target number first `a=input()` - this has to be stored in a variable.
It then sorts the input with the function `lambda x:abs(a-x)` applied (think `map(lambda x:abs(a-x), input())`)
It then takes the minimum value in case of any duplicate values
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÍñaV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=zfFhVg&input=WzUgLTVdCjA)
```
ÍñaV     :Implicit input of array U and integer V
Í        :Sort U
 ñ       :Sort by
  aV     :  Absolute difference with V
         :Implicit output of first element
```
[Answer]
# [Python 3](https://docs.python.org/3/), 41 bytes
```
lambda n,a:min((abs(n-i),i)for i in a)[1]
```
[Try it online!](https://tio.run/##HYtBCoRADATvviLHDkRwHOYi7EvcPURkMLBGUS/7@tHZY3VV779r2TyW/HqXr67TrOSiw2oO6HTCW2MxzttBRuakPIZPqfhkdUASBOklMguhE7RBoqQ/9VWlqoaGaD/ML2Q8R@ZyAw "Python 3 – Try It Online")
No need to sort, because `min` captures the lowest difference *and* the lowest value.
Also works in [Python 2](https://tio.run/##HYtBCoRADATvviLHDkRwRuYi7EvcPURkMLBGUS/7@tHZY3VV779r2TyW/HqXr67TrOSiw2oO6HTCW2MxzttBRuakPIZPqfhkdUASBInSMwuhE7RBekl/ilWlqoaGaD/ML2Q8R@ZyAw "Python 2 – Try It Online").
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes
```
◄≠⁰O
```
[Try it online!](https://tio.run/##yygtzv7//9H0lkedCx41bvD///@/0f9oUx1jHcNYAA "Husk – Try It Online")
```
◄           # element that minimizes
 ≠⁰         # difference to arg 1
   O        # applied to sorted elements
            # (implicitly) of arg 2
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{I.x
```
[Try it online](https://tio.run/##yy9OTMpM/f@/2lOv4v//aFMdXVMdQ4NYLgMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkAAX/VxfrVfzX@R8dHW2oY6RjHKtjGqujEB2ta6hjDGIagHmGOqYgKSNkjq6hkTFEqSlCoamOLpgdCwA).
**Explanation:**
```
{     # Sort the first (implicit) input-list from lowest to highest
  .x  # Pop the list, and push the value closest
 I    # to the second input-integer
      # (after which it is output implicitly as result)
```
This could have been 2 bytes (`.x`) if we were allowed to output the first instead of the lowest value in the list, if more than one is closest: [try it online](https://tio.run/##yy9OTMpM/f9fr@L/f11DI2OuaEMdUx3jWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJvzXq/iv8z86OtpQx0jHOFbHNFZHITpa11DHGMQ0APMMdUxBUkbIHF1DI2OIUlOEQlMdXTA7FgA).
[Answer]
# TeaScript, 10 bytes
```
T#(y-l)a)░
```
TeaScript doesn't support array input so in the console run: `TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS)` to runthis.
## Explanation
```
T#  // Sort input by...
  (y-l)a // absolute difference with input
)░  // First item in array
```
[Answer]
# R, 42 bytes
```
x=sort(scan());x[which.min(abs(x-scan()))]
```
[Answer]
## Haskell, 38 bytes
```
e#l=snd$minimum$(zip=<<map(abs.(e-)))l
```
Usage example: `2 # [1,5,3]`-> `1`.
For each element in the input list `l` make a pair of the absolute difference of the element with the input number `e` and the element itself, e.g. `e=2`, `l=[1,5,3]` -> `[(1,1),(3,5),(1,3)]`. Find the minimum and discard the difference.
[Answer]
## zsh, ~~75~~ ~~73~~ ~~71~~ ~~70~~ 67 bytes
```
for n in ${@:2};{echo "$[$1-n]    $n"}|tr -d -|sort -n|head -1|cut -f2
```
Expects input as command line arguments.
Note that the four spaces in the `echo` is actually supposed to be a tab, but Stack Exchange converts tabs to spaces in all posts.
Not Bash-compatible because of the `for` syntax.
```
for n in ${@:2};      for each argument except the first...
{echo "$[$1-n]\t$n"}  output the difference from the first argument
                        and then the original number
|tr -d -              poor man's abs()
|sort -n              sort by first num (difference), tiebreaking by second num
                        (original value)
|head -1              take the thing that sorted first
|cut -f2              print field 2 (aka discard the difference)
```
Thanks to [dev-null](https://codegolf.stackexchange.com/users/48657/dev-null) for 2 bytes!
[Answer]
# [Perl 6](http://perl6.org), 31 bytes
```
{@^b.sort.sort((*-$^a).abs)[0]}
```
### Usage:
```
my &code = {@^b.sort.sort((*-$^a).abs)[0]}
say code 5, [1,2,3];   # 3
say code 0, [-1,3,5];  # -1
say code 2, [1, 5, 3]; # 1
say code 0, [5,-5];    # -5
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ôXêUe>┤
```
[Run and debug it](https://staxlang.xyz/#p=93588855653eb4&i=5,%5B1,2,3%5D%0A0,%5B-1,3,5%5D%0A2,%5B1,5,3%5D%0A0,%5B5,-5%5D&m=2)
[Answer]
# [PHP](https://php.net/), 62 bytes
```
foreach($a as $i){$s[$i]=abs($i-$n);}
asort($s);print key($s);
```
[Try it online!](https://tio.run/##HccxCoQwEAXQPqdI8YsEtNAts9GDiMUoSsJCHGZsZPHsEXzd48T1O3JigxI/wYAiidDluqb3oe6HbLQmB7KkFtn/oRPyHGlRh9yi@HAb0kNOB/WBJZfT/rbrXR2H@gA "PHP – Try It Online")
First PHP answer, please help!
*(Define the number and array in header section)*
[Answer]
# [T-SQL](https://docs.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver15), 93 Bytes
```
SELECT MIN(B) FROM(SELECT B,abs(B-@v) AS C FROM @A) D WHERE C=(SELECT MIN(abs(B-@v)) FROM @A)
```
Example:
```
DECLARE @A TABLE(B  INT);
DECLARE @v INT = 5;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3)) AS A(B);
SELECT MIN(B) -- 3. Finally, select the minimum list value from the rowset
FROM(
        SELECT B,abs(B-@v) AS C -- 1. Get list value along with absolute value of the difference.
        FROM @A
    ) D
WHERE C = (SELECT MIN(abs(B-@v)) -- 2. Filter for the smallest absolute difference.
          FROM @A
          )
```
[Answer]
# C# ~~61~~ 52 bytes
```
int v(int i,int[] a)=>a.Min(x=>(Math.Abs(i-x),x)).x;
```
Or function body only: 29 bytes.
]