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!

1

4 Answers 4

1

maybe with a function like that :

function removeByKey(array, params){

  return array.filter( item => item[params.key] !== params.value)
}
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

0

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

Comments

0

ES5 version of @Jayfee answer:

 function removeByKey(array, params){

    return array.filter(function (item) {
      return item[params.key] !== params.value;
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.