Rob
Rob

Reputation: 1636

JavaScript Deleting all objects from an array which contain a value

I have an obj, with an array of objects - something like below (I've not pasted it here because its HUGE). I'm trying to loop through the array of objects - deleting those objects from the array which contain a value. I have written the following code... (using lodash)

When looping over the array its randomly missing a few 'Foo's - so not all the Foo objects are deleted... even though they contain the key Foo. It does ignore that which doesn't contain Foo though.

obj = {
      array : [
         {
          key1 : 'Foo',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi',
          Key3 : 'blah'
         },
         {
          key1 : 'Fred',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi'
         }
         ... etc....
      ]
}

  var items = obj.array
  _.forEach(items, function(n, index) {
   var isFoo = _.includes(n, 'Foo');
   console.log(isFoo);
   if (isFoo) {
      items.splice(index, 1);
    }
  });

Upvotes: 0

Views: 62

Answers (2)

Rob
Rob

Reputation: 1636

I ditched lodash, and just did a reverse for-loop (my thinking was that as things were being removed, the index would change... and maybe that was causing the errors?)

var items = obj.array;
var i;
for (i = items.length - 1; i >= 0; i -= 1) {
    if (items[i].type === 'Foo') {
        items.splice(i, 1);
    }
}

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

I suspect things are getting confused because you are changing the array at the same time as you are looping through it.

_.remove is probably a better option for you here:

var obj = {
      array : [
         {
          key1 : 'Foo',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi',
          Key3 : 'blah'
         },
         {
          key1 : 'Fred',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi'
         }
      ]
};

_.remove(obj.array, function(n, index) {
    return _.includes(n, 'Foo');
});

console.dir(obj.array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>

Upvotes: 1

Related Questions