title: Array of Objects ordered by similarity to neighbour
body: <p>I really hope you can help me I have an array of objects and I need an algorithm or a pointer to something to read up on that will sort them by similarity to their neighbours.</p>
  
  <p>For Example</p>
  
  <pre><code>[ 
    {a:12,b: 7,c: 5}, 
    {a: 5,b: 5,c: 5}, 
    {a: 3,b: 3,c: 3}, 
    {a: 5,b: 7,c: 5},
    {a:12,b: 7,c: 5}
  ]
  </code></pre>
  
  <p>becomes</p>
  
  <pre><code>[
    {a: 5,b: 5,c: 5},
    {a: 5,b: 7,c: 5},
    {a:12,b: 7,c: 5}, 
    {a:12,b: 7,c: 5}, 
    {a: 3,b: 3,c: 3},
  ]
  </code></pre>
  
  <p>I have a REPL here...</p>
  
  <p><a href="https://repl.it/@idrise/ThoseWellmadeMonitors" rel="nofollow noreferrer">https://repl.it/@idrise/ThoseWellmadeMonitors</a></p>
  
  <p>I have brute forced it but it doesn't get the best score and it takes eons on big arrays.</p>
  
  <p>This is how the score is calculated, the higher the score the better !</p>
  
  <pre><code>function scoreArray(array) {
    let score = 0;
    for (let f = 1; f &lt; array.length; f++) {
      score += howSimilarAreObjects(array[f - 1], array[f]);
    }
    return score;
  }
  
  function howSimilarAreObjects(object1, object2) {
    let score = 0;
    Object.keys(object1).forEach(curValue =&gt; {
      if (object1[curValue] === object2[curValue]) {
        score++;
      }
    });
    return score;
  }
  </code></pre>
  
  <p>Any help greatly appreciated,</p>
  
  <p>Idris</p>