title: Javascript sort custom comparator function - sorting a sorted array
body: <p>I have an array of objects of the following form:</p>
  
  <pre><code>arr[0] = { 'item1' : 1234, 'item2' : 'a string' };
  </code></pre>
  
  <p>I sort it first by <code>'item1'</code> which is straightforward. Now i want to sort <code>arr</code> (which is sorted by <code>'item1'</code>) again but this time by <code>'item2'</code> but only for the elements where <code>'item1'</code> is the same. The final array would look like:</p>
  
  <pre><code>arr = [
    { 'item1' : 1234, 'item2' : 'apple' },
    { 'item1' : 1234, 'item2' : 'banana' },
    { 'item1' : 1234, 'item2' : 'custard' },
    { 'item1' : 2156, 'item2' : 'melon' },
    { 'item1' : 4345, 'item2' : 'asparagus' } 
  ];
  </code></pre>
  
  <p>I tried to write a sorting function for the second case like so:</p>
  
  <pre><code>arr.sort(function(a,b){
    if(a.item1 === b.item1){
      return a.item2 &gt; b.item2 ? 1 : a.item2 &lt; b.item2 : -1 : 0;
    }
  });
  </code></pre>
  
  <p>I could combine the two sorts in one function to get the final sorted array but there will be cases where I'll have to sort by just <code>'item1'</code> or just <code>'item2'</code>.  </p>