Find the closest smaller array

I think I want it quite simple, but I can not find the right solution.

I have such an array in Javascript:

[0, 38, 136, 202, 261, 399] 

And I get the generated value from 0 to 600 when the button is clicked. I need to find the nearest lower value in this array.

For example, if the generated value is 198, I want to get the result 136. If the generated value is 300, I want 261 ... If it is 589, I want 399, etc. Etc.

So far I have tried with this code:

 var theArray = [ 1, 3, 8, 10, 13 ]; var goal = 7; var closest = null; $.each(theArray, function(){ if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) { closest = this; } }); alert(closest); 

But it only returns the closest value ... Now I need to get only the closest lower value for a given number ... How can I improve my algorithm according to my needs?

Thanks!

+5
source share
3 answers

If the array is sorted and small enough, a very simple way to do what you want is to make it easier to iterate through the array until number > number-in-array returns the number at the previous position.

 function getClosestValue(myArray, myValue){ //optional var i = 0; while(myArray[++i] < myValue); return myArray[--i]; } 

Sincerely.

+3
source

You can use Array#some and exit if the element is greater than or equal to the desired value. Otherwise, assign the actual value as the return value.

This suggestion works for sorted arrays.

 function getClosest(array, value) { var closest; array.some(function (a) { if (a >= value) { return true; } closest = a; }); return closest; } var array = [0, 38, 136, 202, 261, 399]; console.log(getClosest(array, 100)); // 38 console.log(getClosest(array, 198)); // 136 console.log(getClosest(array, 300)); // 261 console.log(getClosest(array, 589)); // 399 
0
source

Cancel the array and use find

 let arr = [0, 38, 136, 202, 261, 399]; let val = 300; let number = arr.reverse().find(e => e <= val); console.log(number); 
0
source

Source: https://habr.com/ru/post/1273665/


All Articles