首页 > 解决方案 > 如何在 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)
        })
    }

标签: javascriptnode.jsarrayssortingdiscord.js

解决方案


要按数字对数组进行排序,您可以使用.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)
}

推荐阅读