How to get the closest element from a javascript array using jQuery? -


i have javascript array this

var array1= [10,20,30,40,50]; 

is there method using can closest array element given number ? ex: if pass 26, should return 30 ( 26 closest 30). if pass 42, should return 40.

any thoughts ? should iterate thru each elements ? there methods available in jquery ?

simple loop. no jquery magic necessary:

function getclosestnum(num, ar) {     var = 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 closest number         return closest;     }     //no length     return false; } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -