Problems when ordering an array in javascript and a chat that I am creating


I'm creating a chat with sockets on nodejs that say it's very good. Then I create an array:

let nicknames = [];

that will save the names of users so that later the frontend will be in charge of showing them in a list. That works perfect for me.

So, I have an event called connection that detects when a user connects to the chat and adds it to the list:

//Cuando un usuario se conecta y el socket escucha
  io.on("connection", socket => {
    socket.on('new user', (data, cb) => {
        console.log("Se conecto "+data);
        if (nicknames.indexOf(data) != -1) {
        } else {
            socket.nickname = data;
        nicknames = nicknames.sort();
        io.sockets.emit("nad", socket.nickname);

Until then everything is fine again, even the .sort () method tells me the users in alphabetical order as it should be. And the function updateNicknames (); is the one in charge of sending the users ordered to the frontend:

function updateNicknames() {
        io.sockets.emit('usernames', nicknames);

so that it shows them in the list in the following way:

socket.on('usernames', data =>{
    let html = '';
    for (let i = 0; i < data.length; i++) {
      html += '<p><i class="fas fa-user"></i> ${data[i]} </p>';

The problem is when I want a user to be disconnected, the last one that came out is always disconnected, regardless of the user that actually disconnects:

socket.on('disconnect', data => {
      if(!socket.nickname) return;
      io.sockets.emit("nod", socket.nickname);

      nicknames.splice(nicknames.indexOf(socket.nickanme), 1);


This line is the one that disconnects the user and then the updateNicknames () is again responsible for sending the list ordered to the frontend.

nicknames.splice(nicknames.indexOf(socket.nickanme), 1);

I do not know why the user I want is not disconnected.

asked by Diesan Romero 23.07.2018 в 05:24

1 answer


I think this is what you need, identify which socket is at the moment of deletion. When the user enters the user's data is assigned with the key (nicknames [] = data)

When the user is disconnected for any reason he removes the object of the array by the allocated socket (delete nicknames [];)

socket.on('new user', (data, cb) => {
  nicknames[] = data

socket.on('disconnect', function () {
  delete nicknames[];
answered by 24.07.2018 / 16:42