Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
Get largest int from object inside of array that's under a limit

I'm currently building a Discord.js bot were I wanna give role rewards depending on what level you reach.

This is my main part of the code to figure out what role to give, which works perfectly when your role rewards only have a 1 level differance (so from 1 to 2), but if I go from level 4 to 5 it doesn't know what to remove and just crashes because prevLvl is undefined.

So basically when you reach a certain milestone it needs to give a new role and remove the previous one.

memberData.level = 4;

levelUpRoles = [ //These ones get pushed in array by user
    {role: 'id1', level: 1},
    {role: 'id2', level: 2},
    {role: 'id3', level: 5},
    {role: 'id4', level: 20},
    {role: 'id5', level: 10},
]

let newLvl = levelUpRoles.find(object => object.level === memberData.level);
let prevLvl = levelUpRoles.find(object => object.level === memberData.level - 1);

if (newLvl) {
    target.roles.add(newLvl.role).catch(console.error);

    target.roles.remove(prevLvl.role).catch(console.error);
}

I hope that this made sense. Thanks in advanced!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Assuming levelUpRoles will consistently be in ascending order, you can check for the index of the lowest level value above memberData.level using the > operator.

Then, from that index, find the new level and previous level and do the necessary operations.

levelUpRoles = [
    {role: 'id1', level: '1'},
    {role: 'id2', level: '2'},
    {role: 'id3', level: '5'},
]

let nextIndex = levelUpRoles.findIndex(object => object.level > memberData.level);
if (nextIndex) {
    nextIndex > 0 || nextIndex = levelUpRoles.length; // If there is no next level

    const newLvl = levelUpRoles[nextIndex-1];
    target.roles.add(newLvl.role).catch(console.error);

    if (nextIndex > 1) { // If there exists a previous level
        const prevLvl = levelUpRoles[nextIndex-2];
        target.roles.remove(prevLvl.role).catch(console.error);
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda