How to find nearest value in an array?

Asked

Viewed 247 times

-1

var dados=[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 4.75, 5.0, 5.7, 6.0, 6.2, 6.5, 7.0, 7.1, 7.5, 8.0];
var DadoMaisPertoDe = 3.8; 
//preciso encontrar o valor 4.0

//outra demanda
//dado o valor encontrado acima (4.0)
//preciso achar dois valores acima e dois abaixo desse valor, dado um intervalo minimo
I=1.0; //intervalo minimo
//preciso achar  [2.0, 3.0, 5.0, 6.0] //lembrando q parte de 4.00 encontrado antes
I=1.5;
//preciso achar  [1.0, 2.5, 5.7, 7.5] 
  1. How do I find the nearest value in an array?
  2. How to find beyond this value, the two values closer to the value I found above, but with a minimum interval (I)?

thanks in advance for the help.

Edited: If anyone else needs help with something like this, I found the solution here: http://jsfromhell.com/pt/array/nearest-number

1 answer

2

Since this looks like college work, I won’t do it, I’ll just show you how to do it.

Taking a quick look, I found the following: https://stackoverflow.com/a/49436218/5565024

As you can see, he says that following the premise that he did not know if he could sort the array, he did so there. However, regardless of whether you don’t want to change the order of the current array, I believe it would be easier to sort the array, and go incrementing or decrementing in a loop to find the next values.

So you can follow the other example where the array is ordered (Sort): https://stackoverflow.com/a/49436066/5565024

With this, just go creating the logic and saving in variables and comparing, the nearest until you get the two before and after the desired value and according to the minimum interval.

Once you get it, post the answer here to help other people.

  • Thanks for the return. The array, will already always be ordered in ascending order and will sometimes be large, with about 700 to 1000 elements. It is not college, I do to meet my needs of my own site, I am not programmer in js. but google and stackoverflow, I manage as I can. I usually find something, but in this case I had found nothing.

  • I think with this example I passed I can get there. I didn’t imagine this possible with reduce. I had imagined with loops, but I believe I could be very heavy to need.

  • Start developing the script, and if you run into a problem, ask for help here in the stack. Since you don’t program in JS, you probably don’t know lodash. You might find it helpful to make the script easier. =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.