What is the easiest way to remove all objects from an array with a particular property = x?
Asked
Active
Viewed 142 times
1
-
2What kind of array? Sample please – Khamidulla Dec 23 '13 at 07:03
-
_.without(array, [*values]) _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); – F.C.Hsiao Dec 23 '13 at 07:06
-
possible duplicate of [Remove array element based on object property](http://stackoverflow.com/questions/15287865/remove-array-element-based-on-object-property) – Khamidulla Dec 23 '13 at 07:10
2 Answers
2
Use _.filter
var result = _.filter(arr, function(item) {
return !("prop" in item);
});
If you want to limit it to the immediate properties of each item, use
var result = _.filter(arr, function(item) {
return !item.hasOwnProperty("prop");
});

maček
- 76,434
- 37
- 167
- 198
0
It seems like the easiest way would be to use the filter
method:
var newArray = _.filter(oldArray, function(x) { return !('prop' in x); });
// or
var newArray = _.filter(oldArray, function(x) { return !_.has(x, 'prop'); });
Or alternatively, the reject
method should work just as well:
var newArray = _.reject(oldArray, function(x) { return 'prop' in x; });
// or
var newArray = _.reject(oldArray, function(x) { return _.has(x, 'prop'); });
Update Given your updated question, the code should look like this:
var newArray = _.filter(oldArray, function(x) { return x.property !== 'value'; });
Or like this
var newArray = _.reject(oldArray, function(x) { return x.property === 'value'; });

p.s.w.g
- 146,324
- 30
- 291
- 331