Is it possible to remove objects from an array using a key/value combination? For instance, removing all "non-active" users from the array?
Here is an example of what the code might look 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);
However, there seems to be an issue when the last entry in the array has "active": false
. It doesn't get removed as expected.
If you have any solutions or suggestions, please feel free to share!