Refactor JS loop