前端面试编程题汇总

题目描述:
给定一个学生列表,学生信息由班级、分数、姓名等组成。请按照下列规则对学生列表进行排序:

  • 按照班级从小到大进行排列
  • 班级相同时,按照成绩从大到小排序
  • 班级和成绩相同时,按照学生列表中的先后顺序排序

输入:学生列表
输出:排序后的学生列表

样例输入:
[{“name”:”张三”,”class”:2,”score”:64},{“name”:”李四”,”class”:1,”score”:80},{“name”:”王五”,”class”:1,”score”:80},{“name”:”赵六”,”class”:4,”score”:94}]

样例输出:
[{“name”:”李四”,”class”:1,”score”:80},{“name”:”王五”,”class”:1,”score”:80},{“name”:”张三”,”class”:2,”score”:64},{“name”:”赵六”,”class”:4,”score”:94}]

代码如下:

function sortStudents(students) {
    // body...
    students.sort((a,b)=>{
        if (a.class===b.class) 
            if (a.score===b.score) 
                return 0;
            else return b.score - a.score;
        else return a.class - b.class;
    });
    return JSON.stringify(students);

}
students = [{"name":"张三","class":2,"score":64},{"name":"李四","class":1,"score":80},{"name":"王五","class":1,"score":80},{"name":"赵六","class":4,"score":94}]
sortStudents = sortStudents(students);
console.log(sortStudents);

你可能感兴趣的:(前端面试)