PSport PSport - 3 months ago 7
Javascript Question

Find the next highest number in array

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.

Answer

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>

Comments