Find Nearest value in Javascript array

Few days back i was working on a diamond trading website that allows customer to choose from a variety of diamonds ie almost more than 90k. One functionality in that the diamond search which is having typical sliders and buttons to choose from various diamond attributes

First client requested the slider to be non uniform, ie non regular intervals for carat.. He is having a range of 0.3 to 20 carats.  So in that he need 0.3 to 1 this range should cover almost 50% or slider range, from 1-2 it should be around 70% or slider range and rest values should be covered in remaining 30%.

The explanation will also post in upcoming posts , but the issue now is that he also need manual input for the carat so one can also type manually in the carat box and then system should able to search for the specific ones

When someone types the value the slider should automatically adjust representing the range and then perform the search.

We used the non uniform interval, so defined each and every value in the array and that is feed to the slider, so if value is not found in array the slider is not getting positioned in correct position.

The simple solution i got is on Stackoverflow and I tried the solution and it worked in perfect manner

The function is much simple

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;
}

The functions takes and argument as array and the value and finds the nearest value in array and returns the same

Now the slider instead of rendering to the extreme values. It takes the nearest value and do the rest.

GITHUB project can be found HERE

Advertisements

What you think ? Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s