refactor loops into findIndex function