Finding closest 2 elements in array by key

+4 votes
35 views
asked Dec 13, 2012 in java script by codeg (2,600 points)

 

I am looking for a function that would search for the closet 2 elements out of an array of object based on a known object value. The function would return the indexes for the 2 closest elements or a single index if there is a direct match. it would search by the p variable in each element.

(It is safe to assume the p variable will not appear more than once)

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

if the value was 60 it would return [2,3]
if the value was 30 it would return [1]

1 Answer

0 votes
answered Dec 13, 2012 by sahana (2,250 points)
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];
};
...