How do Remove Element From an Array – Simple

/**
Set - New Array
*/
const users = [];

/**
* Add - New Element/Item
*/
users.push({ id: socket.id, name: 'Visitor'});
 
/**
* Find - Index of Element
*/
var foundIndex = users.findIndex(x => x.id == socket.id);

/**
* Update/Add - New Data an Founded Element
*/
users[foundIndex].name = data.name;

/**
* Remove
*/
users.splice(foundeIndex, 1);

Example from My Home Hobby Project:

const users = [];

nsp.on('connection', (socket) => {
    console.log('Kullanici :' + socket.id + 'Baglandi');
    users.push({ id: socket.id, name: 'Visitor'});

    socket.on('sendUserData', (data) => {
        console.log('Server => ' + data.name + ' Connected.');
        var foundIndex = users.findIndex(x => x.id == socket.id);
        users[foundIndex].name = data.name;

        nsp.emit('updateUserList', users);
    });
    
    socket.on('sendMessage', (data) => {
        console.log(data);
    });

    socket.on('disconnect', ()=> {
        var foundIndex = users.findIndex(x => x.id == socket.id);
        users.splice(foundIndex, 1);
        nsp.emit('updateUserList', users);
    });

    console.log(users);
});

 

Views: 443