Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  95] [ 6]  / answers: 1 / hits: 14111  / 10 Years ago, thu, july 31, 2014, 12:00:00

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 2200 would return 3000 (NOT 2000).



However, if I search for 3200 as there is nothing higher in the array, it should return 3000 as there are no other choices.



I can get the closest number that is under the value using:



if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
sizeToUse = this;
}


However, I can't get the whole thing to work. My full code is:



$(function() {

var monitorWidth = window.screen.availWidth,
sizeToUse = null,
upscaleImages = false;

$('.responsive-img').each(function(){

var sizeData = $(this).attr('data-available-sizes');
sizeData = sizeData.replace(' ', '');

var sizesAvailable = sizeData.split(',');
sizesAvailable.sort(function(a, b){return b-a});

$.each(sizesAvailable, function(){
if(upscaleImages){
if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
sizeToUse = this;
}
}
else{
//We don't want to upscale images so we need to find the next highest image available
}

});

console.log('Size to use ' + sizeToUse + ' monitor width ' + monitorWidth);

});


});

More From » javascript

 Answers
4

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/


[#43454] Wednesday, July 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierceabnerc

Total Points: 430
Total Questions: 92
Total Answers: 102

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;