I
I
ingenerdsm2017-08-15 10:28:31
git
ingenerdsm, 2017-08-15 10:28:31

How to find the closest element of an array in Javascript?

Hello, tell me how you can find the array element closest to the variable (you need to get the value and index of the array element), example:
arr = [0, 2, 5, 10]; //array
x = 7; //variable
Accordingly, the closest element to the specified variable will be the element with value 5 and index 2.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Y
Yaroslav Bilionok, 2019-04-08
@slava_des

In short, we write:
git remote rm origin
git remote add origin [email protected]:username/myapp.git
and then our path

P
Pavel Kornilov, 2017-08-15
@ingenerdsm

var val=7;
[0, 2, 5, 10].reduce(function(a,c) {
  return Math.abs(a-val) < Math.abs(c-val) ? a: c;
})

A
alexandzolotarev, 2017-08-15
@alexandzolotarev

Array.prototype.reduce()

N
Negwereth, 2017-08-15
@Negwereth

Bust. Calculate the delta and remember the index when the delta is less than the previously memorized one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question