Search code examples
debuggingdiscorddiscord.jsembedleaderboard

when i sort an array its all jumbled up? DISCORD JS


i can’t find any docs or anything on this issue. I’m using VSC and discord.JS and I’m doing a leaderboard system. The goal is when a user types !top, a leaderboard(that is embedded) pops up with the top 10 people with the most money.this works every first time after a reload(only sometimes), but after that the .sort doesn’t work and the leaderboard stats are reshuffled somewhere else, and someone with $0 is at the top. here is my code:

    if (msg.content.startsWith("!top")) {
        let moneyC = [];
        let embedT = new Discord.MessageEmbed();
        let membersCurrent = 0;

        msg.guild.members.cache.forEach(element => {
            money.fetchBal(element.id).then((i) => {
                membersCurrent++;
                moneyC.push({ name: element.user.username, moneyT: i.money });
                if (membersCurrent >= msg.guild.memberCount) {
                    moneyC.sort((a, b) => b.money - a.money);
                    for (i = 0; i < 10; i++) {
                        embedT.addField("---", moneyC[i].name + " = " + moneyC[i].moneyT);
                    }
                }
                if (membersCurrent == msg.guild.memberCount) {
                    membersCurrent++;
                    sendEmbed();
                }
            })
        });

        function sendEmbed() {
            console.log(moneyC);
            embedT.setDescription("here are the top 10 people with the highest balance!")
            msg.channel.send(embedT);
            moneyC = [];
        }
    }

and here is the console output AND the discord output for the 1st and 2nd time:

CONSOLE:

 { name: 'TheBigCringeMaster', moneyT: 100 },
   { name: 'PogchampInRealLife', moneyT: 0 },
   { name: 'bluestone', moneyT: 0 },
   { name: 'Birdie_YT', moneyT: 0 },
   { name: 'iDopeyScope', moneyT: 0 },
   { name: 'Lewcyる', moneyT: 0 },
   { name: 'Aretimis', moneyT: 0 },
   { name: 'Cam S', moneyT: 0 },
   { name: 'IAmABoomer', moneyT: 0 },
   { name: '$HOO!ER_SavgE', moneyT: 0 },
   { name: 'AwokenYt', moneyT: 0 },
   { name: 'Wingyman2019', moneyT: 0 },
   { name: 'I LOVE EINAR - owo', moneyT: 0 },
   { name: 'Lilly', moneyT: 0 },
   { name: 'Reaction Roles', moneyT: 0 },
   { name: 'boobieman123', moneyT: 0 },
   { name: 'Jamelfarm', moneyT: 0 }

(these are some of my discord members)

AND here is the discord output @TheBigCringeMaster is me and always has the most money:

here is the image = img


Solution

  • The issue is that you are switching moneyT and moneyaround,

    moneyC.sort((a, b) => b.money - a.money); => moneyC.sort((a, b) => b.moneyT - a.moneyT);

    As shown by:

    moneyC.push({ name: element.user.username, moneyT: i.money })