js实现排名
实现排名功能的方法
在JavaScript中实现排名功能通常涉及对数据进行排序、分组和分配名次。以下是几种常见的方法:
基于数组排序的简单排名

const scores = [85, 92, 78, 92, 88];
const ranked = [...scores]
.sort((a, b) => b - a)
.map((score, index) => ({ score, rank: index + 1 }));
处理并列排名的实现
function calculateRanks(scores) {
const sorted = [...scores].sort((a, b) => b - a);
const ranks = {};
let currentRank = 1;
sorted.forEach((score, index) => {
if (index > 0 && sorted[index-1] !== score) {
currentRank = index + 1;
}
ranks[score] = ranks[score] || currentRank;
});
return scores.map(score => ranks[score]);
}
对象数组的排名实现

const students = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 92 },
{ name: 'Charlie', score: 78 }
];
const rankedStudents = [...students]
.sort((a, b) => b.score - a.score)
.map((student, index) => ({
...student,
rank: index + 1
}));
分组排名实现
function groupRank(items, key) {
const sorted = [...items].sort((a, b) => b[key] - a[key]);
let rank = 1;
return sorted.map((item, i) => {
if (i > 0 && sorted[i-1][key] !== item[key]) {
rank = i + 1;
}
return { ...item, rank };
});
}
带并列排名的优化版本
function getRankings(scores) {
const uniqueScores = [...new Set(scores)].sort((a, b) => b - a);
const rankMap = new Map();
uniqueScores.forEach((score, index) => {
rankMap.set(score, index + 1);
});
return scores.map(score => rankMap.get(score));
}
这些方法可以根据具体需求进行调整,比如处理降序或升序排名、处理大量数据时的性能优化等。对于更复杂的排名系统,可能需要考虑使用专门的库或数据库查询来实现。






