1

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

Steven Dropper
  • 467
  • 3
  • 15

2 Answers2

6

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));
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

Here's a simple way which avoids any difficulties of modifying-while-iterating and good runs in good old O(n):

var removeByPid = function(cart, pid) {
  var result = [];
  for (var i = 0, len = cart.length; i < len; i++)
    if (cart[i].pid !== pid) result.push(cart);
  return result;
};

Now you can say:

var cart = /* ... get values for cart somehow ...  */

// ... Do more stuff ...

cart = removeByPid(cart, 1234);
Gershom Maes
  • 7,358
  • 2
  • 35
  • 55