Lim SY Lim SY - 6 months ago 40
Javascript Question

Removing element from multidimensional array or object in javascript

I have a rooms object, inside that object has many rooms array, and in each room there are users element.

var rooms = {"room1":["user1","user2"],"room2":["user1","user2","user3"]};

How do I write a function that remove a specific user from the rooms array when called?

function leaveRoom(user,room){
if(typeof room != "undefined"){
//remove user from the specific room ONLY if room argument is passed
} else {
//remove user from all rooms

I have tried to use splice with the index of the element but it doesn't work.

Array.prototype.remove = function(value) {
if (this.indexOf(value)!==-1) {
this.splice(this.indexOf(value), 1);
return true;
} else {
return false;
var roomName="room1",

actually I'm not even sure if it is an object or array anymore. Please help thanks


You can use loop, delete, Array.prototype.filter() to remove element having value undefined from array

var rooms = {
  "room1": ["user1", "user2"],
  "room2": ["user1", "user2", "user3"]

function leaveRoom(user, room, obj) {
  if (room && Array.isArray(obj[room])) {
    delete obj[room][obj[room].indexOf(user)];
  } else {
    for (var prop in obj) {
      delete obj[prop][obj[prop].indexOf(user)];
  for (var prop in obj) {
      obj[prop] = obj[prop].filter(Boolean)

leaveRoom("user1", "room1", rooms);

console.log(rooms); // remove `"user1"` from `"room1"`
// pass `null` as second parameter to remove `user` from all rooms
leaveRoom("user2", null, rooms); // remove `"user2"` from all rooms