Search code examples
javascriptarraysobjecteachsplice

Remove all objects from array with a specific key value


I've been literally struggling for a day, literally a whole day searching the entire stackoverflow and google to try and solve this issue but I'm desperate. I've tried dozens of solutions but none of them seem to work...

I've got an array of objects where each object has a key named pid with a certain value. Now I'd like to delete all objects with the same, specific pid value.

I've tried forEach, filter, $.each, $.grep and many other functions to try to solve this issue, all of them unsuccessful (or maybe I'm doing something wrong every time?)

Simply, I want to remove each object with a specific pid value. My current code is:

$.each(cart, function(i){
        if(cart[i].pid === pid){
            cart.splice(i,1);
        }
    });

But this one keeps throwing: Cannot read property pid of undefined

Other functions delete only a (random?) amount of objects, there are still some left overs in the array with the unwanted pid value.

I don't necessarily have to stick with the $.each function, so any solution is greatly appreciated.

Array of objects:

[{"id":1523898500862,"amm":1,"type":"t","name":"bluecheese","pid":1523898494726,"cost":0.5},{"id":1523898501937,"amm":1,"type":"t","name":"edam","pid":1523898494726,"cost":0.5},{"id":1523898505766,"amm":1,"type":"t","name":"mozzarella","pid":1523898494726,"cost":1}]

As you can see all the three objects hold the same pid value, I want to delete them all, according to that pid


Solution

  • filter() is your solution. It takes a callback as an argument that decides if the element should be kept in the array and returns the filtered array.

    function remove(arr, pid) {
      return arr.filter(e => e.pid !== pid);
    }
    
    let arr = [{ pid: 1 }, { pid: 2 }];
    console.log("Removed pid:1", remove(arr, 1));
    console.log("Removed pid:2", remove(arr, 2));
    console.log("Removed pid:3", remove(arr, 3));
    
    let yourArr = [{
      "id": 1523898500862,
      "amm": 1,
      "type": "t",
      "name": "bluecheese",
      "pid": 1523898494726,
      "cost": 0.5
    }, {
      "id": 1523898501937,
      "amm": 1,
      "type": "t",
      "name": "edam",
      "pid": 1523898494726,
      "cost": 0.5
    }, {
      "id": 1523898505766,
      "amm": 1,
      "type": "t",
      "name": "mozzarella",
      "pid": 1523898494726,
      "cost": 1
    }];
    console.log("Removed from your array", remove(yourArr, 1523898494726));