在我的结果中,学生应该按 Room-Id 分组(!),然后在组内按年龄排序。
按房间分组/排序的结果:
Name | R | Age
-------------------
Student 2 | 1 | 22
Student 4 | 1 | 25
Student 3 | 3 | 21
Student 6 | 3 | 27
Student 1 | 5 | 29 <- Wrong, should be: Student 5, Room 5, Age 23
Student 5 | 5 | 23 <- Wrong, should be: Student 1, Room 5, Age 29
我当前的代码(JSFiddle:http: //jsfiddle.net/n9KNx/):
<script type="text/javascript">
/* 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 < b.room_id) ? -1 : ((a.room_id > b.room_id) ? 1 : 0));
});
/* FIXME: sort by age without changing the room order */
/* ... code ... */
/* build HTML output */
var html = '<table>';
html += '<tr><th>Name</th><th>Room</th><th>Age</th></tr>';
for (var i = 0; i < students.length; i++) {
html += '<tr><td>'+ students[i].name +'</td><td>'+ students[i].room_id +'</td> <td>'+ students[i].age +'</td></tr>';
}
html += '</table>';
$("#students").html(html);
</script>
<div id="students">...</div>
您将如何按年龄对每个组中的学生进行排序?我在 JSFiddle 上添加了代码,请随意使用!