0

I have a sorted list of numbers. I want to search the array for a number (lets call it searchVal). So the line of code below works fine if the number is in the array.

var sPos = $.inArray(searchVal, MyArray);

However if it is not in MyArray I want to select the next biggest number, i.e

I'm searching for 8 in the list below I would like it to return 10.

4, 5, 6, 10, 11

I am new to javascript and wondering what the best way to achieve this is? I have seen a filter could be used where any number >= to 8 is returned and then take the min number from this filtered list. Or is this a case when I should make use of the reduce function?

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
mHelpMe
  • 6,336
  • 24
  • 75
  • 150
  • 2
    Possible duplicate of [using jquery, how would i find the closest match in an array, to a specified number](https://stackoverflow.com/questions/3561275/using-jquery-how-would-i-find-the-closest-match-in-an-array-to-a-specified-num) – Carsten Løvbo Andersen Jun 25 '18 at 10:41
  • Another possible duplicate : [Javascript find closest number in array without going under](https://stackoverflow.com/questions/25061543/javascript-find-closest-number-in-array-without-going-under) – Yann39 Jun 25 '18 at 10:42

4 Answers4

8

You can use Array.find() on sorted array.

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

console.log([13, 4, 6, 5, 10, 11].sort((a, b) => a > b).find(x => x > 8));
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

Since the array is sorted you can use

var num = MyArray.find(x => x > 8)
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Kiran k g
  • 946
  • 11
  • 19
0

For unsorted data, you could take the absolute delta of an item and check with the delta of last item and return the one with smaller delta.

var array = [5, 4, 11, 6, 10],
    find = 8,
    nearest = array.reduce((a, b) => Math.abs(a - find) < Math.abs(b - find) ? a : b);
    
console.log(nearest);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-2

Hi you use the map function to determine the distance to 8.

var array = [4, 5, 6, 10, 11];
var distanceArray = array.map(function(element){
var distance = 8-element
if(distance < 0){
distance = distance * -1;
}
return distance;
})

then you got [4,3,2,2,3]. use Math.min

var minimum = Math.min(...distanceArray);

Now you got 2 as minimum. now found the position

var position = distanceArray.indexOf(minimum);

now you can see whats number is nearest,

var nearest = array[position];

got you 6....

Flo rian
  • 148
  • 10