Skip to content

How can I sort this array in Discord.js?

I have an array, that looks like this(size changes):

[
  { '385090261019131915': 34 },
  { '746430449240375297': 2 },
  { '810189312175374408': 1 },
  { '830832432680009789': 8 },
  { '850073735272988692': 1 }
]

The first value is the member id, the second how many messages the user has. How can I sort the array, to get the first 10 members, sorted by their messages send? The code:

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)
        })
    }

Answer

To sort an array by numbers, you can use the .sort() method with a compare function that subtracts the second value from the first one:

const arr = [34, 2, 1, 8, 1]
const sorted = arr.sort((a, b) => b - a)

console.log({ sorted })

As you’re using objects, you should sort by an object key, but you’re using the user ID as the key, so you don’t know them. You can, however, get the value using the [Object.values()][2] method to get the value(s) and sort by them:

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 })

Don’t forget that Object.values() returns an array so you’ll need to compare the first element.

However, instead of using the user ID as the key and the points as the value, I’d use two different keys in the object, one for the ID and one for the score:

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 })

And the final code:

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)
}