Why is this object array not being ordered? (JS | Bot for Discord)

Asked

Viewed 59 times

0

I’m trying to make a bot for Discord. The command I’m doing does the following (It’s a voting system):

1-You quote who will be a candidate.

2-The bot sends in the same channel the people mentioned in different messages.

3-You vote reacting to someone.

4-The most voted person wins.

And it was managing to do this, the problem is in step 4. The bot should put each message with its reactions (votes) in an array. Then he takes a property that has in every reaction,

.Count -> That’s how much of the same reaction was made.

And it sorts the array according to the amount of votes (Count), and then it takes the first item of the array (which would be this message with more reactions). But it’s not working, the code is as follows:

 setTimeout(() => {
    //voted_colls -> É toda reação que ele coletou. Ele é um array, e cada item é uma collection de 
    //um objeto.
    voted_colls = voted_colls.sort((a, b) => {
      if (a.first().count > b.first().count){
        return 1;
      } 
      if (a.first().count < b.first().count){
        return -1;
      }
      return 0;
    });
    
    let impostor = voted_colls[0].first().message.mentions.users.first();

  }, 10550);
} 

Well, in my vision I had to pick up the first item already ordered and it was all right. But he doesn’t order, I’ve tried several methods to order.

This image expresses the command (almost) ready (The only problem as already said, is that the result did not come out the most voted):

inserir a descrição da imagem aqui

Yes, my command is an Among Beacon 9-9

1 answer

0


The ordering is correct and working, the "problem" is that with the ordering criteria you have implemented you make it order in an increasing way, but you want a decreasing ordering and for that just reverse the signals.

asd = [{count:2},{count:3},{count:4},{count:1}]

// Crescente
asd.sort((a,b) => {
  if(a.count > b.count) return 1;
  if(a.count < b.count) return -1;
  return 0
})
console.log(asd[0]) // {count: 1}


asd = [{count:2},{count:3},{count:4},{count:1}]

// Decrescente
asd.sort((a,b) => {
  if(a.count < b.count) return 1;
  if(a.count > b.count) return -1;
  return 0
})
console.log(asd[0]) // {count: 4}

In your case it is still possible to simplify the code.

asd = [{count:2},{count:3},{count:4},{count:1}]

// Decrescente simplificada
asd.sort((a,b) => {
  return b.count - a.count;
})
console.log(asd[0]) // {count: 4}

  • Vlw! With your tip and some tweaks worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.