简体   繁体   中英

how i can sort user by role in javascript?

I'm running Rocket Chat system in developer version and I need to sort users by role to keep top levels like ( admin / owner / moderator) in the top list, not by online status because the default sort is

    // show online users first.
    // sortBy is stable, so we can do this
    users = _.sortBy(users, u => u.status == null);

I need to change this code to sort by role level and this example for user data in users.json

"type" : "user", 
"status" : "offline", 
"active" : true, 
"name" : "Super", 
"_updatedAt" : ISODate("2017-05-16T15:10:30.559+0000"), 
"roles" : [
    "admin"
]

in this screenshot user with red is admin and in black is member and i need to move admin in top enter image description here

Typically, sorting is handled by providing a comparer function. This function simply takes two objects, A and B, and determines their relative placement. You as the programmer decide the logic used to determine the ordering.

Here's an example based on your description.

const roleComparer = (a, b) => {
  if (a.roles.includes('admin') && !b.roles.includes('admin')) {
    return 1;
  }
  else if (b.roles.includes('admin') && !a.roles.includes('admin')) {
    return -1;
  }
  else {
    return 0;
  }
};

To sort, you simply pass it into the Array.prototype.sort() method as the argument:

users = users.sort(roleComparer);

What the sort() method does is it walks through the array one index at a time, and applies the comparer function you provide. It compares the current index (argument a) with the next one (argument b). If it returns 1, a is greater. If -1, less. If 0, they're equal.

This is not unique to javascript, but is how sorting/comparing is handled in many languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM