Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an item from an array by value

I have an array of items like:

var items = [id: "animal", type: "cat", cute: "yes"]

And I'm trying to remove any items that match the ID given. In this case; animal

I'm stuck! I can get it to work easily by having a more simpler array but this is not what I need... I also need to remove the item by value as I don't want the hassle of referring to items by their index.

Is there a jQuery method I could use where I don't need to iterate through the items array, rather specify a selector?

Here is my jsFiddle: http://jsfiddle.net/zafrX/

like image 498
Alex Guerin Avatar asked Jan 15 '12 21:01

Alex Guerin


People also ask

How do I remove a specific part of an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do I remove a specific element from an array in Python?

You can use the pop() method to remove an element from the array.

Can you remove from an array?

To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array. The following implementation shows removing the element from an array using ArrayList.


1 Answers

I'm not sure how much of a hassle it is to refer to array items by index. The standard way to remove array items is with the splice method

for (var i = 0; i < items.length; i++)
    if (items[i] === "animal") { 
        items.splice(i, 1);
        break;
    }

And of course you can generalize this into a helper function so you don't have to duplicate this everywhere.


EDIT

I just noticed this incorrect syntax:

var items = [id: "animal", type: "cat", cute: "yes"]

Did you want something like this:

 var items = [ {id: "animal",  type: "cat", cute: "yes"}, {id: "mouse",  type: "rodent", cute: "no"}];

That would change the removal code to this:

for (var i = 0; i < items.length; i++)
    if (items[i].id && items[i].id === "animal") { 
        items.splice(i, 1);
        break;
    }
like image 58
Adam Rackis Avatar answered Oct 14 '22 16:10

Adam Rackis