Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the highest role from array

I currently have an array u._roles that is filled with id's from groups like "581199939464462340". Secondly I have a dictionary where the key is a role id and the value is the name, like {key: "581199939464462340", value: "Member"}.

Now I want to get the name of the "highest" role of the array. Currently I have this ugly if statement but I think that can be done better, but how? (The array u._roles is read only).

u._roles could look like this:

["5812040340469414946", "581200340469415946", "581209222700597248"] so the "highest" would be "581200340469415946" (second if). (And then get the name of this id from the dictionary roleMap)

var Rank;

if (u._roles.includes("581199939464462340")) {
    Rank = roleMap["581199939464462340"]; // highest
} else if (u._roles.includes("581200340469415946")) {
    Rank = roleMap["581200340469415946"]; //
} else if (u._roles.includes("581214123334041620")) {
    Rank = roleMap["581214123334041620"]; // 
} else if (u._roles.includes("588976480017448988")) {
    Rank = roleMap["588976480017448988"]; //
} else if (u._roles.includes("581203853635223574")) {
    Rank = roleMap["581203853635223574"]; // 
} else if (u._roles.includes("581209222700597248")) {
    Rank = roleMap["581209222700597248"]; // 
} else if (u._roles.includes("592436270031175681")) {
    Rank = roleMap["592436270031175681"]; // lowest
} else {
    Rank = "";
}

Highest don't mean the highest number. Its just an order I like to use.

like image 669
TakeAMinute Avatar asked Dec 06 '25 14:12

TakeAMinute


1 Answers

I completely changed this answer with some new insight. Hopefully this is a bit more helpful.


const rolePriority = {a:1, b:2, c:3, d:4};
const u = {"_roles": ['b','c', 'a']};

const rankNumber = u._roles.reduce((highest, role) => {
  const rank = rolePriority[role];
  return rank < highest ? rank : highest;
}, Infinity);

const rank = rankNumber === Infinity ? "" : roleMap[rankNumber]

like image 101
ktilcu Avatar answered Dec 09 '25 03:12

ktilcu