JS 实现 rank
ts

JS 实现 rank

TypeScript 示例代码:在上面的示例中,我们在 Student 接口中添加了一个 rank 属性,表示学生的名次。在 rank 函数中,我们使用一个变量 currentRank 来追踪当前的名...

花野猫

花野猫

更新于 2023-07-24

1835

TypeScript 示例代码:

typescript
interface Student {
name: string;
score: number;
rank: number; // 添加 rank 属性
}
function rank(students: Student[]): Student[] {
students.sort((a, b) => b.score - a.score);
// 遍历排序后的学生数组,为每个学生对象添加名次
let currentRank = 1;
for (let i = 0; i < students.length; i++) {
const student = students[i];
student.rank = currentRank;
// 如果下一个学生分数和当前学生分数相同,则名次不变
if (i < students.length - 1 && student.score === students[i + 1].score) {
continue;
}
currentRank++;
}
return students;
}
// 示例用法
const studentScores: Student[] = [
{ name: 'Alice', score: 85, rank: 0 },
{ name: 'Bob', score: 72, rank: 0 },
{ name: 'Charlie', score: 90, rank: 0 },
{ name: 'David', score: 65, rank: 0 },
{ name: 'Eve', score: 78, rank: 0 }
];
const rankedStudents = rank(studentScores);
console.log(rankedStudents);

在上面的示例中,我们在 Student 接口中添加了一个 rank 属性,表示学生的名次。在 rank 函数中,我们使用一个变量 currentRank 来追踪当前的名次,然后在遍历学生数组时为每个学生对象设置相应的名次。如果有多个学生分数相同,它们将被分配相同的名次。最后,我们将结果打印到控制台上。

请注意,我们在示例用法中将 rank 属性初始化为 0,但在 rank 函数中会被正确地更新。这样,你就可以在返回的学生数组中看到每个学生的名次信息了。

使用 Lodash:

typescript
import _ from 'lodash';
interface Student {
name: string;
score: number;
rank: number; // 添加 rank 属性
}
function rank(students: Student[]): Student[] {
const sortedStudents = _.orderBy(students, 'score', 'desc');
const groupedStudents = _.groupBy(sortedStudents, 'score');
let currentRank = 1;
const rankedStudents = _.flatMap(groupedStudents, (group) => {
const rankedGroup = _.map(group, (student) => ({
...student,
rank: currentRank
}));
currentRank += group.length;
return rankedGroup;
});
return rankedStudents;
}
// 示例用法
const studentScores: Student[] = [
{ name: 'Alice', score: 85, rank: 0 },
{ name: 'Bob', score: 72, rank: 0 },
{ name: 'Charlie', score: 90, rank: 0 },
{ name: 'David', score: 65, rank: 0 },
{ name: 'Eve', score: 78, rank: 0 },
{ name: 'Frank', score: 90, rank: 0 },
{ name: 'Grace', score: 78, rank: 0 }
];
const rankedStudents = rank(studentScores);
console.log(rankedStudents);

我们首先使用 groupBy 函数将学生数组按照分数进行分组。然后,我们使用 flatMap 函数遍历每个分组,并为每个学生对象设置相应的名次。在设置名次时,我们使用一个变量 currentRank 来追踪当前的名次,并根据分组的长度更新名次值。

这样,无论学生的分数是否相同,都能正确地为每个学生设置名次。