Posted in

Buscar el valor más cercano dentro de un array

function nearest(arr, checkval) {
if (arr.length<=1) {
return 0;
}
near = null;
neardiff = null;
for (x=0; x<arr.length; x++) {
diff = Math.abs(arr[x]-checkval);
//trace("Diff:"+diff);
if (diff<=neardiff || neardiff == null) {
neardiff = diff;
near = x;
}
}
return near;
//return near-1;
}

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *


The reCAPTCHA verification period has expired. Please reload the page.