Discord.js: Is there a function that can check whether the user has a rank from the array of ranks

Viewed 381

I'm currently working on a discord bot that has multiple commands that are only for specific roles. I currently have all roles that are allowed to use the commands in an array and my code below works.

        for (var i = 0; i < Config.AllowedRanks.length; i++) {
            if (message.member.roles.cache.has(Config.AllowedRanks[i])){
                console.log("Access Granted")
        }
     }

But how do I make it so that everyone else that doesn't have the role, gets a message that the access is denied? The code below does the thing I want but also does it when someone has the role when that role is not first in the array.

        for (var i = 0; i < Config.AllowedRanks.length; i++) {
            if (message.member.roles.cache.has(Config.AllowedRanks[i])){
                console.log("Access Granted")
        } else{
                console.log("Access Denied")
        }
     }

The answer thanks to Bqre:

        if (Config.AllowedRanks.some(role => message.member.roles.cache.get(role))){
            console.log("Access Granted")
        } else{
            console.log("Access Denied")
        }
1 Answers

For this specific case, we would want to use the .some() method, that loops through an entire array and checks if at least one of the elements matches a certain condition.

For example, let's create an array of role IDs:

const roles = ['id1', 'id2', 'id3'];

What we can do from here, is take the array we have created, and check if the author has at least one of the roles with one of the IDs above using the .some() method.

Final Code

const roles = ['id1', 'id2', 'id3'];
if (roles.some(role => message.member.roles.cache.get(role))) console.log('Access Granted.');
else console.log('Access Denied.');

Respectively, the same would work for the .every() method, that instead checks if all of the elements of an array match the condition - In our case, if the user has all of the roles above.

Related