Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda