0

I am setting an element in an array like this:

dialogs[id] = $.modal({
    title: "Admin",
    closeButton: true,
    content: content,
    width: false,
    resizeOnLoad: true,
    buttons: {
        'Close': function (win) {
            win.closeModal();
        }
    }
}).find('form') // Attach logic on forms
.submit(formSubmitHandler)
.end();

Later on I check if exists like this:

if (!dialogs[id]) {
    loadAndShowDialog(id, link, url);
}

How can I remove the id record from the dialogs array? Is there something like a dialogs[id].Remove() ?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
  • You will need to use `splice()`, see first answer here: http://stackoverflow.com/questions/500606/javascript-array-delete-elements – Armatus Apr 23 '12 at 08:02

4 Answers4

3

the command is : (set it to undefined)

delete dialogs[id];

if you want to completely remove : use splice.

edit

I mistakely thought that its is an object property which you want to remove ( delete will be fine here - and only solution)

howevert - you have an Array and the correct answer is to use splice.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    Be aware that `delete` does not actually *remove* the element but rather replaces it with `undefined`. – Armatus Apr 23 '12 at 08:06
1

I suggest you take a look at this tutorial. It explains really well how to play with arrays in javascript.

The delete method doesn't delete an element, it just replaces it with undefined. To delete elements from an array, you need splice.

According to MDN, here is how to use it:

array.splice(index , howMany[, element1[, ...[, elementN]]])

So, you need the index where you want to start deleting, and howMany is the number of elements you want to delete.

For your case, it'd be:

dialogs.splice( dialogs.indexOf( id ), 1 )

Note the use of indexOf to find out the index of the id value.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0

You can use

delete dialogd[id]; //will not remove element, will set it to undefined

or

dialogs.splice(id,1); //will not work in case of non-numeric indices

Choose whichever one is appropriate. I prefer the second.

Manishearth
  • 14,882
  • 8
  • 59
  • 76
0

when removing an item from an array, use splice

dialogs.splice(id,1); //remove "1" item starting from index "id"

note that this removes the item, and changes the array length. so in an array of 3, if i spliced this way, the array will now have a length of 2.

using delete will not affect the array, but leave that location undefined. it's like "unsetting" or "leaving a hole" in that location.

delete dialogs[id];  //value at index "id" is now undefined 
Joseph
  • 117,725
  • 30
  • 181
  • 234