I have a javascript array like this
var array1= [10,20,30,40,50];
Is there any method using which i can get the closest array element to a given number ? Ex: if i pass 26, It should return 30 ( 26 is closest to 30). If i pass 42, It should return 40.
Any thoughts ? Should i iterate thru each elements ? Is there any methods available for this in jQuery ?
Simple with a for loop. No jQuery magic necessary:
function getClosestNum(num, ar)
{
var i = 0, closest, closestDiff, currentDiff;
if(ar.length)
{
closest = ar[0];
for(i;i<ar.length;i++)
{
closestDiff = Math.abs(num - closest);
currentDiff = Math.abs(num - ar[i]);
if(currentDiff < closestDiff)
{
closest = ar[i];
}
closestDiff = null;
currentDiff = null;
}
//returns first element that is closest to number
return closest;
}
//no length
return false;
}
If performance is a concern (very large array) and the array is ordered (as in the example), you may want to consider a Binary Search. You can probably find one pre-written for javascript but may need to modify slightly to handle your "closest" piece once the algorithm reaches the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With