title: Sorting array of objects by property to match a provided list
body: <p>Given an array of objects and a list of values, I want to effectively sort the object so that values of a unique property (say <code>key</code>) follows the order of values in the list.</p>
  <p>So for an array:</p>
  <pre><code>const users = [
    { key: 'A', name: 'Alice' },
    { key: 'B', name: 'Bob' },
    { key: 'C', name: 'Charlie' },
  ]
  </code></pre>
  <p>I'd like the function to behave like this:</p>
  <pre><code>sortByList(['A', 'B', 'C'], users)
  // -&gt; Objects for Alice, Bob, Charlie
  
  sortByList(['C', 'B', 'A'], users)
  // -&gt; Objects for Charlie, Bob, Alice
  
  sortByList(['A', 'C', 'B'], users)
  // -&gt; Objects for Alice, Charlie, Bob
  </code></pre>
  <hr />
  <p>I came up with an implementation that uses <code>Array::sort</code> on the array and then inside <code>Array::indexOf</code> on the list.</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>const users = [
    { key: 'A', name: 'Alice' },
    { key: 'B', name: 'Bob' },
    { key: 'C', name: 'Charlie' },
  ]
  
  const sortByList = (list, arr) =&gt; arr.sort(
    (a, b) =&gt; list.indexOf(a.key) - list.indexOf(b.key)
  );
  
  sortByList(['C', 'B', 'A'], users)
  
  console.log(users)</code></pre>
  </div>
  </div>
  </p>
  <p>But I feel this is not an effective solution. The time complexity is O(N^2*log(N)) which is rather high. Is there a better one?</p>
  <p>I do not care about in-place sorting or stability, imagine the array has tens to hundreds of items.</p>