Javascript find closest number in array without going under

前端 未结 3 1199
花落未央
花落未央 2021-01-12 02:59

I have an array of numbers, for example [300, 500, 700, 1000, 2000, 3000] and I want to find the closest number, without going under the number given.

F

相关标签:
3条回答
  • 2021-01-12 03:16

    You can use this code :

    function closest(arr, closestTo){
    
        var closest = Math.max.apply(null, arr); //Get the highest number in arr in case it match nothing.
    
        for(var i = 0; i < arr.length; i++){ //Loop the array
            if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i]; //Check if it's higher than your number, but lower than your closest value
        }
    
        return closest; // return the value
    }
    
    var x = closest(yourArr, 2200);
    

    Fiddle : http://jsfiddle.net/ngZ32/

    0 讨论(0)
  • 2021-01-12 03:21
    var list = [300, 500, 700, 1000, 2000, 3000];
    
    function findBestMatch(toMatch) {
        // Assumes the array is sorted.
    
        var bestMatch = null;
        var max = Number.MIN_VALUE;
        var item;
    
        for (var i = 0; i < list.length; i++) {
            item = list[i];
    
            if (item > toMatch) {
                bestMatch = item;
                break;
            }
    
            max = Math.max(max, item);
    
        }
    
        //  Compare to null, just in case bestMatch is 0 itself.
        if (bestMatch !== null) {
            return bestMatch;
        }
    
        return max;
    
    }
    
    alert(findBestMatch(2200));
    alert(findBestMatch(3200));
    
    0 讨论(0)
  • 2021-01-12 03:24
     sizesAvailable.sort(function(a, b){return a-b});  // DESCENDING sort
    
    if(upscaleImages)   // do th eif once, not every time through the loop
    {
        $.each(sizesAvailable, function()
        {  
            if (this > monitorWidth) 
                sizeToUse = this;
        }
        if (sizeToUse == null) sizeToUse = sizesAvailable[0];
    }
    else
    {
        $.each(sizesAvailable, function()
        {  
            //We don't want to upscale images so....
        }
     }
    });
    
    0 讨论(0)
提交回复
热议问题