1

What is the easiest way to remove all objects from an array with a particular property = x?

el_pup_le
  • 10,711
  • 22
  • 77
  • 130

2 Answers2

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
  • 73,409
  • 36
  • 162
  • 195
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
  • 141,205
  • 29
  • 278
  • 318