Reputation: 4144
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!
Upvotes: 0
Views: 81
Reputation: 4144
ES5 version of @Jayfee answer:
function removeByKey(array, params){
return array.filter(function (item) {
return item[params.key] !== params.value;
});
}
Upvotes: 0
Reputation: 138267
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)
Upvotes: 1
Reputation: 1279
maybe with a function like that :
function removeByKey(array, params){
return array.filter( item => item[params.key] !== params.value)
}
Upvotes: 1