0

I'm trying to remove objects from an array based on a key/value combination - in my case to remove all "non-active" users.

Example code looks like

    var items = [ 
      { "userID":"694","active": false }, 
      { "userID":"754","active": true }, 
      { "userID":"755","active": true },
      { "userID":"760","active": false },
      { "userID":"761","active": false },
      { "userID":"762","active": false }
      ]
    
        function removeByKey(array, params){
          array.some(function(item, index) {
            return (array[index][params.key] !== params.value) ? !!(array.splice(index, 1)) : false;
          });
          return array;
        }
    
     for (var i = 0; i < items.length; i++){ 
     
     var removed = removeByKey(items, {
          key: 'active',
          value: true
        });
    }
    
        console.log(removed);

But each time when last entry in the array contains "active": false, it will not be removed.

Any help is appreciated!

Linny
  • 818
  • 1
  • 9
  • 22
JackTheKnife
  • 3,795
  • 8
  • 57
  • 117
  • Possible duplicate of [How to filter array when object key value is in array](https://stackoverflow.com/questions/35817565/how-to-filter-array-when-object-key-value-is-in-array) – ergonaut Jul 23 '18 at 16:09

4 Answers4

1

maybe with a function like that :

function removeByKey(array, params){

  return array.filter( item => item[params.key] !== params.value)
}
Jayffe
  • 1,269
  • 9
  • 13
1

Because if you remove an element (lets say the second last), then the for loop will skip the next one as its index gets smaller. If you want to stay with your custom remover function you have to call it like this:

let previous;
do {
    previous = items.length;
    removeByKey(items, {
      key: 'active',
      value: true
    });
 } while(previous !== items.length)

But thats actually quite inefficient, so you should modify the method that it removes all occurences and not just the first found (forEach instead of some, or just filter it)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

var filteredItems = items.filter(item => item.active);

0

ES5 version of @Jayfee answer:

 function removeByKey(array, params){

    return array.filter(function (item) {
      return item[params.key] !== params.value;
    });
}
JackTheKnife
  • 3,795
  • 8
  • 57
  • 117