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,4235 gold badges34 silver badges32 bronze badges
asked Apr 23, 2012 at 7:59
1

4 Answers 4

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.

answered Apr 23, 2012 at 8:01
Sign up to request clarification or add additional context in comments.

1 Comment

Be aware that delete does not actually remove the element but rather replaces it with undefined.
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.

answered Apr 23, 2012 at 8:10

Comments

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 
answered Apr 23, 2012 at 8:09

Comments

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.

answered Apr 23, 2012 at 8:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.