JavaScript:按密钥对项目进行分组,按其他密钥对(!)组内的项目进行排序 – 如何?

在我的结果中,学生应按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上添加了代码,随意玩吧!

最佳答案
排序功能需要扩展到房间相等时.当房间相等时,我们然后比较年龄.

students.sort(function(a, b) {
    if(a.room_id < b.room_id){
        return -1;  
    }else if(a.room_id > b.room_id){
        return 1;
    }else{
        if(a.age < b.age){
           return -1
        }else if(a.age > b.age){
          return 1;
        }else{
          return 0;
        }
    }
});

工作实例http://jsfiddle.net/n9KNx/1/

转载注明原文:JavaScript:按密钥对项目进行分组,按其他密钥对(!)组内的项目进行排序 – 如何? - 代码日志