按键查找数组中最接近的2个元素

时间:2012-06-13 06:13:49

标签: javascript jquery arrays object

我正在寻找一个函数,它将根据已知的对象值从对象数组中搜索closet 2元素。如果存在直接匹配,则函数将返回2个最接近元素的索引或单个索引。它将通过每个元素中的p变量进行搜索。

(可以安全地假设p变量不会出现多次)

var orbit = [ // p is percent
    { p:   0, x:   0, y:   0, z: 1.2 }  
    { p:  30, x:  30, y: 100, z: 0.5 }  
    { p:  45, x: 100, y:  30, z: 0.7 }  
    { p:  75, x:  60, y:   0, z: 1.0 }  
    { p: 100, x:   0, y:   0, z: 1.2 }  
];

function ValueToIndexes (value) {
    return [close1, close2];
};

如果值为60,则返回[2,3]
如果值为30,则返回[1]

2 个答案:

答案 0 :(得分:1)

或许这样的事情:

function ValueToIndexes(orbit, value) {
    var sorted = orbit.sort(function (obj1, obj2) {
        return Math.abs(obj1.p - value) - Math.abs(obj2.p - value);
    });

    if (sorted[0].p === value)
        return [sorted[0]];

    return [sorted[0], sorted[1]];
};

答案 1 :(得分:1)

var ValueToIndices = function (orbit, value) {

    var 
        /* storage for distances */
        distances = [],

        /* sort helper */ 
        sortByDistance = function (a, b) {
            return a.d - b.d;
        };

    /* iterate over orbit */
    for (var i = 0; i < orbit.length; i++) {

        /* a direct match returns immediately */
        if (orbit[i].p === value) {
            return [i];
        }

        /* else collect all distances to the value */
        distances.push({
            i: i,
            d: Math.abs(orbit[i].p - value)
        });
    }

    /* sort the distances */
    distances.sort(sortByDistance);

    /* return the indices of the first two */
    return [distances[0].i, distances[1].i];
};