前端面試程式設計題彙總
阿新 • • 發佈:2019-02-10
題目描述:
給定一個學生列表,學生資訊由班級、分數、姓名等組成。請按照下列規則對學生列表進行排序:
- 按照班級從小到大進行排列
- 班級相同時,按照成績從大到小排序
- 班級和成績相同時,按照學生列表中的先後順序排序
輸入:學生列表
輸出:排序後的學生列表
樣例輸入:
[{“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);