Delete from array in javascript

What you have is an Array. You should use the splice() method to remove an element from an array, not by deleteing the element.

for (var i = 0; i < Roomdata.length; i++) {

    if(Roomdata[i].id = X) {

        Roomdata.splice(i, 1);
        break;

    }
}  

Using splice in spite of delete.

 Roomdata.splice(i, 0);

splice attribute removes blank string elements, undefined references, NULLs and FALSEs.

it will solve your problem


Walk through the array in reverse order, and use .splice to remove the element.
You have to walk in the reverse order, because otherwise you end up skipping elements See below.

for (var i = Roomdata.length-1; i >= 0; i--) {
    if (Roomdata[i].id == X) {
        Roomdata.splice(i, 1);
        break;
    }
}

What happens if you don't walk in the reverse order:

// This happens in a for(;;) loop:
// Variable init:
var array = [1, 2, 3];
var i = 0;

array.splice(i, 1); // array = [2, 3]   array.length = 2
// i < 2, so continue
i++;  // i = 1    

array.splice(i, 1); // i=1, so removes item at place 1: array = [2]
// i < 1 is false, so stop.

// array = [2]. You have skipped one element.

Tags:

Javascript