js实现排名
实现数组元素排名
在JavaScript中,可以通过排序和映射的方式为数组元素生成排名。以下是一个常见的实现方法:
function rankArray(arr) {
// 创建带有原始索引的副本
const indexedArr = arr.map((value, index) => ({value, index}));
// 按值降序排序
indexedArr.sort((a, b) => b.value - a.value);
// 分配排名
const ranks = new Array(arr.length);
indexedArr.forEach((item, i) => {
ranks[item.index] = i + 1; // 排名从1开始
});
return ranks;
}
// 示例用法
const scores = [85, 92, 78, 92, 88];
const rankings = rankArray(scores);
console.log(rankings); // 输出: [3, 1, 5, 1, 4]
处理并列排名
对于有相同值的元素,通常需要相同的排名,可以使用以下方法处理并列情况:
function rankArrayWithTies(arr) {
const indexedArr = arr.map((value, index) => ({value, index}));
indexedArr.sort((a, b) => b.value - a.value);
const ranks = new Array(arr.length);
let currentRank = 1;
for (let i = 0; i < indexedArr.length; i++) {
if (i > 0 && indexedArr[i].value !== indexedArr[i-1].value) {
currentRank = i + 1;
}
ranks[indexedArr[i].index] = currentRank;
}
return ranks;
}
// 示例用法
const scores = [85, 92, 78, 92, 88];
const rankings = rankArrayWithTies(scores);
console.log(rankings); // 输出: [3, 1, 5, 1, 4]
复杂对象的排名
当需要基于对象属性进行排名时,可以这样实现:
function rankByProperty(arr, prop) {
const indexedArr = arr.map((item, index) => ({
value: item[prop],
index,
original: item
}));
indexedArr.sort((a, b) => b.value - a.value);
const ranked = [];
let currentRank = 1;
indexedArr.forEach((item, i) => {
if (i > 0 && item.value !== indexedArr[i-1].value) {
currentRank = i + 1;
}
ranked.push({
...item.original,
rank: currentRank
});
});
return ranked;
}
// 示例用法
const students = [
{name: 'Alice', score: 85},
{name: 'Bob', score: 92},
{name: 'Charlie', score: 78},
{name: 'David', score: 92},
{name: 'Eve', score: 88}
];
const rankedStudents = rankByProperty(students, 'score');
console.log(rankedStudents);
分组排名
对于需要分组内进行排名的情况,可以使用以下方法:
function groupRank(data, groupKey, rankKey) {
const groups = {};
// 按组分类
data.forEach(item => {
const group = item[groupKey];
if (!groups[group]) groups[group] = [];
groups[group].push(item);
});
// 每组内排名
Object.values(groups).forEach(group => {
group.sort((a, b) => b[rankKey] - a[rankKey]);
let currentRank = 1;
group.forEach((item, i) => {
if (i > 0 && item[rankKey] !== group[i-1][rankKey]) {
currentRank = i + 1;
}
item.rank = currentRank;
});
});
return data;
}
// 示例用法
const salesData = [
{region: 'North', salesperson: 'John', sales: 150},
{region: 'North', salesperson: 'Jane', sales: 200},
{region: 'South', salesperson: 'Mike', sales: 180},
{region: 'South', salesperson: 'Sarah', sales: 220},
{region: 'North', salesperson: 'Tom', sales: 200}
];
const rankedSales = groupRank(salesData, 'region', 'sales');
console.log(rankedSales);






