title: An algorithm to find the closest values in javascript array
body: <p>I'm working on a small algorithm to find the closest values of a given number in an random array of numbers. In my case I'm trying to detect connected machines identified by a 6-digit number ID ("123456", "0078965", ...) but it can be useful for example to find the closest geolocated users around me.</p>
  
  <p>What I need is to list the 5 closest machines, no matter if their IDs are higher or lower. This code works perfectly but I'm looking for a smarter and better way to proceed, amha I got to much loops and arrays.</p>
  
  <pre><code>let n = 0; // counter
  let m = 5; // number of final machines to find
  
  // list of IDs founded (unordered: we can't decide)
  const arr = ["087965","258369","885974","0078965","457896","998120","698745","399710","357984","698745","789456"] 
  let NUM = "176789" // the random NUM to test
  
  const temp = [];
  const diff = {};
  let result = null;
  
  // list the [m] highest founded (5 IDs)
  for(i=0 ; i&lt;arr.length; i++) {
      if(arr[i] &gt; NUM) {
          for(j=0 ; j&lt;m; j++) {
              temp.push(arr[i+j]);
          } break;
      }
  }
  
  // list the [m] lowest founded (5 IDs)
  for(i=arr.length ; i&gt;=0; i--) {
      if(arr[i] &lt; NUM) {
          for(j=m ; j&gt;=0; j--) {
              temp.push(arr[i-j]);
          } break;
      }
  }
  
  // now we are certain to get at least 5 IDs even if NUM is 999999 or 000000
  
  temp.sort(function(a, b){return a - b}); // increase order
  
  for(i=0 ; i&lt;(m*2); i++) {
      let difference = Math.abs(NUM - temp[i]);
      diff[difference] = temp[i]; // [ 20519 : "964223" ]
  }
  
  // we now get a 10-values "temp" array ordered by difference
  // list the [m] first IDs:
  
  for(key in diff){
      if(n &lt; m){
          let add = 6-diff[key].toString().length; 
          let zer = '0'.repeat(add);
          let id = zer+diff[key]; // "5802" -&gt; "005802"
          result += (n+1)+":"+ id +" ";
          n+=1;
      }
  }
  
  alert(result);
  
  -&gt; "1:0078965 2:087965 3:258369 4:357984 5:399710" for "176789"
  </code></pre>