2
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.

Utku Cansever
  • 180
  • 2
  • 16

2 Answers2

1

iterate over all elements and switch the shortest element and return it at the end:

function findClosestPair(elements,search_element) {
    var shortestDistance, shortestDistanceIndex;

  elements.forEach((el, index) => {
    distance = Math.sqrt(Math.pow(el[0] - search_element[0], 2) + Math.pow(el[1] - search_element[0], 2));
    if (shortestDistance === undefined || distance < shortestDistance) {
      shortestDistance = distance;
      shortestDistanceIndex = index;
    }
  });

  return elements[shortestDistanceIndex];
}

You can see this work here => https://jsfiddle.net/q8738b9a/

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
1

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392