-2

I have an array of numbers and a value. I'd like to find the numbers around the value. The most important is the highest value but I need both.

var array = [2,4,5,8,11];
var value = 9;

The result I need should be : 8 and 11.

How can I do that?

Thanks.

Huangism
  • 16,278
  • 7
  • 48
  • 74
PSport
  • 139
  • 10

3 Answers3

4

Just write a simple for-loop searching for each of the values.

So for example:

function findNumbers(arr, num){
    var low = num + 1; //largest number lower than num, set initial value above num
    var high = num - 1; //smallest number higher than num, set initial value below num
    for(var i = 0; i < arr.length; i ++){
         if(arr[i] > low && arr[i] < num){
             low = arr[i];
         }
         if(arr[i] < high && arr[i] > num){
             high = arr[i];
         }
    }

    //optional check to see if low/high exists
    if(low > num){
        low = -1; //not found
    }
    if(high < num){
        high = -1; //not found
    }
    return [low,high];

}

and there you go. This works whether or not arr is sorted.

Ted
  • 746
  • 1
  • 7
  • 19
2

This help you :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script>
        
        var array = [2,4,5,8,11];
        
        var value = 9;
        
        var min,max;
        
        fun();
        
        function fun() {
            
            var sortArray = array.sort(function(a,b){return a-b});
            
            for(var i=0; i<sortArray.length;i++) {
                
                if (sortArray[i] < value)
                    min = sortArray[i];
                
                if (sortArray[i] > value)
                    max = sortArray[i];
            }
            
            alert(min + " , " + max);
        }
        
    </script>
</body>
</html>
Ehsan
  • 12,655
  • 3
  • 25
  • 44
1

Looking at your question looks like you are still learning jquery.However I am sure you will get good suggestions here.

Here is an example with your test case,I am leaving the explanation on you so that you can study each line and learn.

var myArray = [2, 4, 5, 8, 11];
var myValue = 9;

function BiggerThan(inArray) {
  return inArray > myValue;
}

function LesserThan(inArray) {
  return inArray < myValue;
}    

var arrBiggerElements = myArray.filter(BiggerThan);
var nextElement = Math.min.apply(null, arrBiggerElements);
alert(nextElement);

var arrLesserElements = myArray.filter(LesserThan);
var prevElement = Math.max.apply(null, arrLesserElements);
alert(prevElement);
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42