title: JavaScript: group items by a key, sort items within(!) the groups by another key - how?
body: <p>in my results Students should be grouped(!) by Room-Id and then, within the group, sorted by age.</p>
  
  <p><strong>Results grouped/sorted by Room:</strong> </p>
  
  <pre><code>Name      | R | Age  
  -------------------
  Student 2 | 1 | 22  
  Student 4 | 1 | 25  
  Student 3 | 3 | 21  
  Student 6 | 3 | 27  
  Student 1 | 5 | 29 &lt;- Wrong, should be: Student 5, Room 5, Age 23 
  Student 5 | 5 | 23 &lt;- Wrong, should be: Student 1, Room 5, Age 29
  </code></pre>
  
  <p>My <strong>current code</strong> (JSFiddle: <a href="http://jsfiddle.net/n9KNx/" rel="noreferrer">http://jsfiddle.net/n9KNx/</a>):</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  /* add students */
  var students = new Array();
  students.push({ name: "Student 1", room_id: 5, age: 29 });
  students.push({ name: "Student 2", room_id: 1, age: 22 });
  students.push({ name: "Student 3", room_id: 3, age: 21 });
  students.push({ name: "Student 4", room_id: 1, age: 25 });
  students.push({ name: "Student 5", room_id: 5, age: 23 });
  students.push({ name: "Student 6", room_id: 3, age: 27 });
  
  /* sort by room_id */
  students.sort(function(a, b) {
      return ((a.room_id &lt; b.room_id) ? -1 : ((a.room_id &gt; b.room_id) ? 1 : 0));
  });
  
  /* FIXME: sort by age without changing the room order */
  /* ... code ... */
  
  /* build HTML output */
  var html = '&lt;table&gt;';
  html += '&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Room&lt;/th&gt;&lt;th&gt;Age&lt;/th&gt;&lt;/tr&gt;';
  for (var i = 0; i &lt; students.length; i++) {
      html += '&lt;tr&gt;&lt;td&gt;'+ students[i].name +'&lt;/td&gt;&lt;td&gt;'+ students[i].room_id +'&lt;/td&gt;    &lt;td&gt;'+ students[i].age +'&lt;/td&gt;&lt;/tr&gt;';
  }
  html += '&lt;/table&gt;';
  
  $("#students").html(html);
  &lt;/script&gt;
  
  &lt;div id="students"&gt;...&lt;/div&gt;
  </code></pre>
  
  <p>How would you sort the students by age within each group? I added the code on JSFiddle, feel free to play with it!</p>