refactor to avoid foreach when filtering