6

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

4

3 回答 3

13

当房间相等时,需要扩展排序功能以覆盖。当房间相等时,我们会比较年龄。

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/

于 2013-05-02T09:01:46.110 回答
5

由于您正在对数字进行排序,因此您无需进行三向比较,只需计算差异即可。解决方案如下所示:

students.sort(function(a, b) {
    return (a.room_id - b.room_id) || (a.age - b.age);
});

…并且与其他答案中的冗长片段完全相同:-)

于 2013-05-02T09:52:14.973 回答
1
students.sort(function(a, b) {
    return ((a.room_id < b.room_id) ? -1 :
              ((a.room_id > b.room_id) ? 1 :
                 ((a.age < b.age) ? -1 :
                    ((a.age > b.age) ? 1 : 0))));
});
于 2013-05-02T09:01:15.793 回答