javascriptarrayssortingclosestclosest-points

Whats fastest way for finding closest number pair in array of pairs


var element_pairs = [[11.333112,22.655543],[35,31231,33.2232],[122352,343421]];
var search_pair = [32,1113,34.5433];
findClosestPair(element_pairs, search_pair);
// [35,31231,33.2232]

what is the fastest way for find mathematicly closest number pair in array of pairs.


Solution

  • You could use Array#reduce and return the tupel which have the smallest delta of all pairs.

    function findClosestPair(elements, search) {
        return elements.reduce(function (a, b) {
            function getDelta(v, w) {
                return Math.abs(v[0] - w[0]) * Math.abs(v[1] - w[1]);
            }                
            return getDelta(a, search) < getDelta(b, search) ? a : b;
        });
    }
    
    
    var elements = [[11.333112, 22.655543], [35.31231, 33.2232], [122352, 343421]],
        search_element = [32.1113, 34.5433];
    
    console.log(findClosestPair(elements, search_element));