如何根据对象属性值将新对象插入JS数组并更新Rank排名?
排行榜新用户插入与排名更新实现
实现逻辑
核心流程分3步:
- 将待插入的新用户追加到原始排行榜数组中
- 按照排名规则对合并后的数组做降序排序:优先比较Speed1,数值越大排名越靠前;Speed1相等时比较Speed2,数值越大排名越靠前
- 遍历排序完成的数组,按顺序给每个用户的
Rank字段赋值为「当前索引+1」(数组索引从0开始,排名从1开始计数)
如果不希望修改原始数组,可以在操作前先对原数组做浅拷贝,避免副作用。
完整代码示例
/** * 向排行榜插入新用户并自动更新所有用户排名 * @param {Array} leaderboard 原始排行榜数组 * @param {Object} newUser 待插入的新用户对象 * @returns {Array} 更新完成的新排行榜 */ function insertUserToLeaderboard(leaderboard, newUser) { // 拷贝原数组避免修改原始数据,不需要保留原数组可直接操作入参数组 const updatedList = [...leaderboard, newUser] // 按排名规则排序 updatedList.sort((a, b) => { // 优先比较Speed1,降序排列 if (b.Speed1 !== a.Speed1) { return b.Speed1 - a.Speed1 } // Speed1相同时比较Speed2,降序排列 return b.Speed2 - a.Speed2 }) // 遍历重写所有用户的Rank值 updatedList.forEach((user, index) => { user.Rank = index + 1 }) return updatedList } // 测试用例 const originLeaderboard = [{ Rank: 1, Speed1: 91, Speed2: 457, Username: 'monizotic', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }, { Rank: 2, Speed1: 91, Speed2: 457, Username: 'Thachtawan', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }, { Rank: 3, Speed1: 91, Speed2: 456, Username: 'PassornSibpang', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }, { Rank: 4, Speed1: 91, Speed2: 456, Username: 'WasinSoikeeree', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }, { Rank: 5, Speed1: 91, Speed2: 454, Username: 'user1055644', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }] const newUser = { Rank: null, Speed1: 91, Speed2: 456, Username: 'thaniman', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null } const newLeaderboard = insertUserToLeaderboard(originLeaderboard, newUser)
运行结果说明
针对给出的测试数据,插入新用户后的排名规则完全匹配原有逻辑:
- Rank1、2:两个Speed2=457的用户保持前两位
- Rank3、4、5:三个Speed2=456的用户(包含新插入的thaniman)排在3-5位
- Rank6:原Speed2=454的用户顺延到第6位
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

