title: Sort an array according to the elements of another array
body: <p>I have an array of ids  </p>
  
  <pre><code>a1 = [1, 2, 3, 4, 5]  
  </code></pre>
  
  <p>and I have another array of objects with ids in random order  </p>
  
  <pre><code>a2 = [(obj_with_id_5), (obj_with_id_2), (obj_with_id_1), (obj_with_id_3), (obj_with_id_4)]  
  </code></pre>
  
  <p>Now I need to sort a2 according to the order of ids in a1. So a2 should now become:  </p>
  
  <pre><code>[(obj_with_id_1), (id_2), (id_3), (id_4), (id_5)]  
  </code></pre>
  
  <p>a1 might be [3, 2, 5, 4, 1] or in any order but a2 should correspond to the order of ids in a1.  </p>
  
  <p>I do like this:  </p>
  
  <pre><code>a1.each_with_index do |id, idx|
    found_idx = a1.find_index { |c| c.id == id }
    replace_elem = a2[found_idx]
    a2[found_idx] = a2[idx]
    a2[idx] = replace_elem
  end  
  </code></pre>
  
  <p>But this still might run into an O(n^2) time if order of elements of a2 is exactly reverse of a1.  Can someone please tell me the most efficient way of sorting a2?</p>