Answer the question
In order to leave comments, you need to log in
How to make top users?
Hello. Got a question. There is a VKontakte bot and a JSON database, all bot users are there, etc. How can you make such a thing like “10 most active users”, and there is already sorting by the number of messages written.
• User 1 | 10 sms
• User 2 | 7 sms
• User 3 | 5 sms
How it is possible to make approximately such sorting?
Answer the question
In order to leave comments, you need to log in
const users = [
{
"id": "1",
"nick": "Паша",
"msg": 30,
},
{
"id": "2",
"nick": "Денис",
"msg": 10,
},
{
"id": "3",
"nick": "Вася",
"msg": 1,
},
{
"id": "4",
"nick": "Пантелеймон",
"msg": 500,
},
{
"id": "5",
"nick": "Володя",
"msg": 5,
}
];
function compareUsers(a, b) {
if (a.msg > b.msg) {
return 1
} else if (a.msg < b.msg) {
return -1
} else {
return 0
}
}
console.log(users.sort(compareUsers)); // по возрастанию
console.log(users.sort(compareUsers).slice().reverse()); // по убыванию
only if all messages are stored in the database, otherwise
bot communities do not save the history of correspondence in conversations
I would advise you to use a normal SQL database instead of a JSON + file.
Since the file may soon grow and add, delete .. operations will require a little more time than necessary.
And so, to work with JSON, you need to know only 2 methods.
JSON.stringify - convert the object to JSON (to a string).
JSON.parse - a string back into an object.
That is, we take your database, run it through parse and get an array with js objects (users).
Then you can, for example, sort and select the first 10 objects.
const top10users = user.sort((a, b)=> (a.messageCount > b.mesaageCount) ? 1 : -1).slice(0,10);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question