Remove an item from an array by value
Asked Answered
G

9

12

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/

Goodbye answered 15/1, 2012 at 21:42 Comment(4)
Your syntax is invalid. Do you have an array or an object? You have mixed the syntax.Aero
If you look in the javascript console (firebug, in my case), it raised that error, 'Uncaught SyntaxError: Unexpected token :' You should create an object Item, and you will be able to access easily attributes of the ItemSlater
object var items = { id: "animal", type: "cat", cute: "yes" }, array var items = ["animal", "cat", "yes" ]Catercornered
My bad! I will remove itWergild
B
27

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;
    }
Bear answered 15/1, 2012 at 21:44 Comment(1)
items.splice(items.indexOf("animals"), 1)Bodrogi
D
11

No need for jQuery or any third party lib for this, now we can use the new ES5 filter :

let myArray = [{ id : 'a1', name : 'Rabbit'}, { id : 'a2', name : 'Cat'}];
myArray = myArray.filter(i => i.id !== 'a1');
Deduct answered 5/10, 2017 at 16:14 Comment(0)
I
6

You can either use splice or run a delete yourself. Here's an example:

for (var i = 0; i < items.length; i ++) {
    if (items[i] == "animal") { 
        items.splice(i, 1);
        break;
    }
}
Issi answered 15/1, 2012 at 21:46 Comment(0)
U
5

There's a simple way!

myItems.splice(myItems.indexOf(myItems.find(row => row.id == id)), 1);

Demo below:

// define function
function delete_by_id(id) {

  var myItems = [{
    id: 1,
    type: "cat",
    cute: "yes"
  }, {
    id: 2,
    type: "rat",
    cute: "yes"
  }, {
    id: 3,
    type: "mouse",
    cute: "yes"
  }];

  // before
  console.log(myItems);

  myItems.splice(myItems.indexOf(myItems.find(item => item.id == id)), 1);

  // after 
  console.log(myItems);

}

// call function
delete_by_id(1);
Ullyot answered 24/7, 2018 at 3:18 Comment(0)
C
3

You should do it like this (make sure that you have the right syntax...you cannot have array with properties, but object inside {} and then you can iterate by keys and delete unwanted key):

var items = {id: "animal", type: "cat", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

for(var p in items){
    if(items[p] === removeItem)
        delete items[p]
}

And to answer you question, you cannot apply jquery selectors to javascript objects. The best you can do to avoid for loop is to use $.each (which is a loop written in a more "functional" way).

Complicated answered 15/1, 2012 at 21:55 Comment(1)
I think this might be the right answer. I missed OP's incorrect syntax.Bear
S
2

By using object notation : http://jsfiddle.net/jrm2k6/zafrX/2/

var animal1 = {id: "animal", type: "cat", cute: "yes"}
var car2 = {id: "car", type: "pick-up", cute: "no"}
var animal3 = {id: "animal", type: "dog", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

var array_items = []
array_items.push(animal1);
array_items.push(car2);
array_items.push(animal3);

for(var i=0;i<array_items.length;i++){
    if(array_items[i].id == removeItem){
        array_items.splice(i,1);
    }
}

//alert(array_items.length);  
Slater answered 15/1, 2012 at 21:56 Comment(0)
T
0

Wow, so many ideas but still not what I wanted xD

This will remove ALL entries of the given value and return the removed value:

function removeOfArray(val, arr){
    var idx;
    var ret;
    while ((idx = arr.indexOf(val)) > -1){
        arr.splice(idx, 1);
        ret = val;
    }
    return ret;
}

Also I found other solutions here: Remove item from array by value

Tamqrah answered 7/8, 2014 at 13:10 Comment(0)
M
0
-parray : list of array of object
-pstring :value to remove from the array
-ptag :using which tag we

function removeFromArr (parray,ptag,pstring){
 var b =[];
var count = 0;
for (var i =0;i<parray.length;i++){
 if(pstring != parray[i][ptag]){
 b[count] = parray[i];
 count++;
 }
}
 return b;
}

var lobj = [ {
 "SCHEME_CODE": "MIP65",
 "YEARS": "1",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.80",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.79"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "2",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.98",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.96"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "3",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "2.05",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "2.03"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "5",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "2.26",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "2.24"
 },
 {
 "SCHEME_CODE": "QIP65",
 "YEARS": "1",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.80",
 "FREQUENCY": "Quarterly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.79"
 },
 {
 "SCHEME_CODE": "QIP65",
 "YEARS": "2",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.98",
 "FREQUENCY": "Quarterly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.97"
 },
]

function myFunction(){
 var final = removeFromArr(lobj,"SCHEME_CODE","MIP65");
 console.log(final);
}
<html>
<button onclick="myFunction()">Click me</button>
</html>

are going to remove from the objects

function removeFromArr(parray, pstring, ptag) {
        var farr = [];
        var count = 0;
        for (var i = 0; i < pa.length; i++) {
            if (pstring != pa[i][ptag]) {
                farr[count] = pa[i];
                count++;
            }
        }
        return farr;
    }
Milomilon answered 9/10, 2019 at 6:49 Comment(1)
Please include an explanation of how and why this solves the problem would really help to improve the quality of your post.Wehrmacht
J
0

ES6 Solution

persons.splice(persons.findIndex((pm) => pm.id === personToDelete.id), 1);
Jojo answered 23/9, 2020 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.