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

Finding closest 2 elements in array by key

本文关键字:元素 最接近 查找 数组      更新时间:2023-09-26

我正在寻找一个函数,该函数将根据已知对象值从对象数组中搜索壁橱 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]

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

也许是这样的:

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