Replace loop with reduce