javascript - 如何在 Discord.js 中对该数组进行排序?
问题描述
我有一个数组,看起来像这样(大小变化):
[
{ '385090261019131915': 34 },
{ '746430449240375297': 2 },
{ '810189312175374408': 1 },
{ '830832432680009789': 8 },
{ '850073735272988692': 1 }
]
第一个值是成员 ID,第二个值是用户拥有多少条消息。如何对数组进行排序,以获取前 10 个成员,按他们发送的消息排序?编码:
if(command === 'leaderboard'){
const list = []
fs.readdirSync('./db/user/messages').forEach(file => {
const user = JSON.parse(fs.readFileSync(`./db/user/messages/${file}` , 'utf-8'))
userid = file.replace('.json','');
const entry = {[userid] : user.userall}
list.push(entry)
})
}
解决方案
要按数字对数组进行排序,您可以使用.sort()
带有比较函数的方法,该函数从第一个值中减去第二个值:
const arr = [34, 2, 1, 8, 1]
const sorted = arr.sort((a, b) => b - a)
console.log({ sorted })
当您使用对象时,您应该按对象键排序,但您使用用户 ID 作为键,因此您不知道它们。但是,您可以使用获取值的[Object.values()][2]
方法获取值并按它们排序:
const arr = [
{ '385090261019131915': 34 },
{ '746430449240375297': 2 },
{ '810189312175374408': 1 },
{ '830832432680009789': 8 },
{ '850073735272988692': 1 }
]
const sorted = arr.sort((a, b) => Object.values(b)[0] - Object.values(a)[0])
console.log({ sorted })
不要忘记它Object.values()
返回一个数组,因此您需要比较第一个元素。
但是,我不会使用用户 ID 作为键,点作为值,而是在对象中使用两个不同的键,一个用于 ID,一个用于分数:
const list = [
{ id: '385090261019131915', score: 34 },
{ id: '746430449240375297', score: 2 },
{ id: '810189312175374408', score: 1 },
{ id: '830832432680009789', score: 8 },
{ id: '850073735272988692', score: 1 }
]
const sortedList = list.sort((a, b) => b.score - a.score)
console.log({ sortedList })
最后的代码:
if (command === 'leaderboard') {
const list = []
fs.readdirSync('./db/user/messages').forEach((file) => {
const user = JSON.parse(
fs.readFileSync(`./db/user/messages/${file}`, 'utf-8'),
)
const userId = file.replace('.json', '')
list.push({ id: userId, score: user.userall })
});
// sort by score
const sortedList = list.sort((a, b) => b.score - a.score)
}
推荐阅读
- html - 让菜单切换垂直而不是水平切换导航栏
- python-3.x - 如何用图像测试我的 CNN 模型?
- maps - 访问历史街景图像
- c - 如何使用 fscanf() 格式字符串
- hibernate - 我的 SpringEclipselink 项目运行良好。我想将 ORM 框架更改为 Hibernate。但它产生了上述问题
- java - Spring Boot中的外键引用主键
- c - 为什么我的编译器(VS2017)选择“CALL-JMP”来访问子程序而不是“CALL”?
- amazon-web-services - 查询 SQL Workbench 访问 Redshift 集群端点 IP 白名单
- android - 引起:java.lang.NoSuchMethodException:
[类 android.app.Application] - viewmodel - c# - 使用任务时是否必须锁定?