Remove code duplication using for-loop