I am working on a multiplayer game and I have a room array with the following layout (I added comments for better understanding):
Room_Array
[
[
"Room_0", // room name
10, // max people
"Random", // room type
[ // now arrays of players follow
[
1, // ShortID
123, // position X
234, // position Y
10 // angle
],
[
2,
123,
234,
10
],
[
3,
123,
234,
10
],
]
]
// here other rooms are created with the same layout as Room_0 when the max people is reached
]
How would I go around to remove the whole array of the player with ShortID = 2? in case he disconnects?
So the desired result would be:
Room_Array
[
[
"Room_0", // room name
10, // max people
"Random", // room type
[ // now arrays of players follow
[
1, // ShortID
123, // position X
234, // position Y
10 // angle
],
[
3,
123,
234,
10
],
]
]
]
I tried the following code and in the console log it showed me the elements of the array I need to splice, so 2, 123, 234, 10. The commented splice resulted in error unidentified element 1.
for (var i = 0; i < Room_Array.length; i++)
{
if (Room_Array[i][0] === PlayerObject[socket.id].RoomName)
{
for (var j = 0; j < Room_Array[i][3].length; j++)
{
if (Room_Array[i][3][j][0] === PlayerObject[socket.id].ShortID)
{
console.log("Array to splice: " + Room_Array[i][3][j]);
//Room_Array.splice([i][3][j], 1); // error unidentified 1
}
}
break;
}
}
Here is a working solution that mutates the initial array.
const Room_Array = [
[
"Room_0", // room name
10, // max people
"Random", // room type
[ // now arrays of players follow
[
1, // ShortID
123, // position X
234, // position Y
10 // angle
],
[
2, // ShortID
123, // position X
234, // position Y
10 // angle
],
[
3,
123,
234,
10
],
]
]
];
function removeUser (array, id) {
array.forEach(room => {
const [roomName, maxPeople, roomType, players] = room;
const index = players.findIndex(([shortId]) => shortId === id);
if(index > -1) {
players.splice(index, 1);
}
});
}
removeUser(Room_Array, 2);
console.log(Room_Array);