user1321237
user1321237

Reputation:

How can I remove an element from an array with javascript / jQuery?

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() ?

Upvotes: 0

Views: 309

Answers (4)

Royi Namir
Royi Namir

Reputation: 148524

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.

Upvotes: 3

Manishearth
Manishearth

Reputation: 16188

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.

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60717

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.

Upvotes: 1

Joseph
Joseph

Reputation: 119837

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 

Upvotes: 0

Related Questions