-2

I have an array of objects:

[
  { content: "lelzz", post_id: "241" },
  { content: "zzyzz", post_id: "242" },
  { content: "abcde", post_id: "242" },
  { content: "12345", post_id: "242" },
  { content: "nomno", post_id: "243" }
]

How can I remove all objects with a post_id of '242'?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Alan Yong
  • 993
  • 2
  • 12
  • 25
  • Here are a few ways to remove an element from an array in javascript: http://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript – rob Feb 11 '14 at 02:23

1 Answers1

1

Two steps:

  1. loop through array backwards
  2. Array.prototype.splice for indices with the matching property
function removeObjectsWithPostId (arr, id) {
    for (var i = arr.length - 1; i > -1; i--) {
        if (arr[i].post_id === id) arr.splice(i, 1)
    }
    return arr
}

If you know that there might be more than one object with this property, you should instead prefer Array.prototype.filter:

function removeObjectsWithPostId (arr, id) {
    return arr.filter(function (obj) { return obj.post_id !== id })
}
royhowie
  • 11,075
  • 14
  • 50
  • 67