Sort array by two properties (JavaScript)

0

I have an array with objects that have the following format:

{
  "username": "Antonio",
  "bot": false
}

I currently have the following code:

guild.members.sort((a, b) => a.user.username > b.user.username ? 1 : -1);

In which, sort the array in alphabetical order, however, I want users whose property bot is true to come first, in alphabetical order.

    
asked by Antonio Roman 16.05.2017 в 10:57
source

2 answers

2

Check this page :

In it they explain how to make the function compareFunction that you pass by parameter to method sort ().

function compare(a, b) {
  // Comparamos la propiedad bot de user.

  if (a.user.bot < b.user.bot) return 1;
  if (a.user.bot > b.user.bot) return -1;
  else {
    // Si la propiedad bot de user es igual, ordenar alfabéticamente.

    if (a.user.username > b.user.username) return 1;
    else if (a.user.username < b.user.username) return -1;
    return 0;
  }
}

This code should work but I have not come to try it.

    
answered by 16.05.2017 / 12:02
source
0
  

I want users whose bot property is true to go first, in alphabetical order.

To handle both criteria at the same time, you can order it 2 times. Depending on the number of records can be an easy alternative to maintain.

Ex.

var members = [
  { bot: false, user: { name: "Bbbbb" }},
  { bot: true, user: { name: "Baaaaa" }},
  { bot: true, user: { name: "Bbbbb" }},
  { bot: false, user: { name: "Baaaaa" }},
  { bot: true, user: { name: "Aaba" }},
  { bot: true, user: { name: "Aaaa" }},
  { bot: false, user: { name: "Aaba" }},
  { bot: false, user: { name: "Aaaa" }}
];

var ordenado = members.sort((a, b) => a.user.username > b.user.username ? -1 : 1)
                      .sort((a, b) => +b.bot-a.bot);

console.log(ordenado);

Note: the + converts the Boolean to number making it easier to compare the case where both Booleans are equal.

    
answered by 16.05.2017 в 13:32