Skip to content Skip to sidebar Skip to footer

Javascript Find Closest Number In Array Without Going Under

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. For instance, searching for 2

Solution 1:

You can use this code :

functionclosest(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 arrayif(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/

Solution 2:

var list = [300, 500, 700, 1000, 2000, 3000];

functionfindBestMatch(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));

Solution 3:

 sizesAvailable.sort(function(a, b){return a-b});  // DESCENDING sortif(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....
    }
 }
});

Solution 4:

Another approach is to find the first candidate greater than or equal to the one you want, and take the result, returning the last element if there are no matches:

functionclosestNumberOver(x, arr) {
    return arr.find(d => d >= x) || arr[arr.length - 1]
  }

Post a Comment for "Javascript Find Closest Number In Array Without Going Under"