title: Swift Arrays: Keeping the order while filtering an array using another
body: <p>I have an array as a list of numbers. In another smaller array I hold some numbers (in a different order) and I'd like to filter my first array using the values in the second array.  </p>
  
  <p><strong>My arrays:</strong>  </p>
  
  <pre><code>let allNumbers = [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
  let someNumbers = [100, 90, 120, 200] // unordered
  </code></pre>
  
  <p>When I use <code>filter</code> method or loop through the values of the first array, I can get the correct values but the order of the elements is not same with my second array but the first -naturally.</p>
  
  <p><strong>Method 1:</strong> <code>filter</code> method, losing order  </p>
  
  <pre><code>let filtered = allNumbers.filter { someNumbers.contains($0) } // Runs 17 times
  print(filtered) // "[90, 100, 120, 200]" (wrong order)
  </code></pre>
  
  <p><strong>Method 2:</strong> Looping through first array, losing order  </p>
  
  <pre><code>var filteredWithLoop: [Int] = []
  for number in allNumbers { // Runs 16 Times
      if someNumbers.contains(number) {
          filteredWithLoop.append(number)
      }
  }
  print(filteredWithLoop) // "[90, 100, 120, 200]" (wrong order)
  </code></pre>
  
  <p><strong>Hack:</strong> I can work this around by filtering the first array when I'm looping through the second, like this:  </p>
  
  <pre><code>var filteredUglyWay: [Int] = []
  for number in someNumbers {
      if let alone = (allNumbers.filter { $0 == number }).first { // Runs 4 * 16 Times
          filteredUglyWay.append(alone)
      }
  }
  print(filteredUglyWay) // "[100, 90, 120, 200]" (correct order)
  </code></pre>
  
  <p>But this feels more like a hack rather than a solution to me especially considering that the loop-ish filter method is called in a loop.  </p>
  
  <p>Is there a better approach for this or is this just how it's supposed to be?  </p>
  
  <p><strong>Important note:</strong> The first array is actually a representation to make the situation more understandable. In my real implementation, first array is holding some objects and the second array is just the ID list of some objects (like favorites of the user) so each time I fetch the whole data, I am trying to filter the favorite objects according to this ID list.</p>