title: JavaScript : Rearrange array elements according to the absolute difference with x
body: <p>Rearrange array elements according to the absolute difference with <strong>x</strong>  i. e., the element having a minimum difference comes first and so on. Like I'm taking 
  array  <strong>[10, 5, 3, 9, 2, 3]</strong> and <strong>x = 7</strong> then the absolute difference for every element should be =</p>
  
  <pre><code>7 - 10 = 3(abs)
  7 - 5 = 2
  7 - 3 = 4
  7 - 9 = 2(abs)
  7 - 2 = 5
  7 - 3 = 4
  </code></pre>
  
  <p>So according to the difference with X, elements are arranged as <strong>[5,9,10,3,3,2]</strong>.</p>
  
  <p>I have tried this by the code below but still failing to do so:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function ar(a, x) {
    var obj = {}, d, i, res;
  
    for (i = 0; i &lt; a.length; i++) {
      d = Math.abs(a[i] - x);
      obj[a[i]] = d;
    }
    
    res = Object.keys(obj).sort(function(a, b) {
      return obj[a] - obj[b]
    });
    
    for (i = 0; i &lt; res.length; i++) {
      res[i] = parseInt(res[i]);
    }
    
    return res;
  }
  
  var o = ar([10, 5, 3, 9, 2, 3], 7);
  console.log(o);</code></pre>
  </div>
  </div>
  </p>
  
  <p>as you can see I'm making object which have only one key but values repeat here .. I can't find another way of solving it the answer I get is <strong>[5,9,10,3,2]</strong>:(..</p>