Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!