Refactored code such that it doesn't destroy the original array