开发者

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

开发者 https://www.devze.com 2023-03-17 05:19 出处:网络
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

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 thou开发者_运维问答ghts ? 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.


Because you have ranges of 10 that are sequential, it can be as simple as this:

var array1= [10,20,30,40,50];
var n = 23;
var idx = Math.max( Math.round( n / 10 ) - 1,  0);

Examples:

var array1= [10,20,30,40,50];
var n = 23;
var idx = Math.max( Math.round( n / 10 ) - 1,  0);

alert( array1[ idx ] );   // 20

var n = 28;
var idx = Math.max( Math.round( n / 10 ) - 1,  0);

alert( array1[ idx ] );   // 30

var n = 1;
var idx = Math.max( Math.round( n / 10 ) - 1,  0);

alert( array1[ idx ] );   // 10

Examples: http://jsfiddle.net/GTrNt/

Should work the same with other ranges, like 25:

var array1= [25,50,75,100,125];
var n = 23;
var idx = Math.max( Math.round( n / 25 ) - 1,  0);

alert( array1[ idx ] );   // 25

var n = 48;
var idx = Math.max( Math.round( n / 25 ) - 1,  0);

alert( array1[ idx ] );   // 50

var n = 1;
var idx = Math.max( Math.round( n / 25 ) - 1,  0);

alert( array1[ idx ] );   // 25

Examples: http://jsfiddle.net/GTrNt/1


http://jsfiddle.net/nwUbV/1/

With binary search. If it's a really big array though, you'll need to implement a better sorting function such as Quicksort so that performance doesn't suffer.


I used jQuery to create the loop (just because I always have jQuery loaded) - it's not really necessary. And this may not be the most efficient method available. But here's a quick function that will do what you need:

var array1 = Array(20, 30, 40, 50);
var closestindex = findClosest(42, array1);
alert('Closest is '+array1[closestindex]);

function findClosest(needle, haystack) {
    var offset = 10000;
    var closest = 0;
    $.each(haystack, function(i) {
        if (haystack[i] <= needle) {
            var localoffset = needle - haystack[i];
        } else {
            var localoffset = haystack[i] - needle;
        }
        if (localoffset <= offset) {
            offset = localoffset;
            closest = i;
        }
    });
    return closest;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消