배열 arr을 받는 getIndex()와 같은 함수를 작성해야 합니다. 문자열/숫자 리터럴 txt 및 숫자 n . txt의 n번째 출현 인덱스를 반환해야 합니다. arr에서 . txt인 경우 n 번 나타나지 않으면 -1을 반환해야 합니다.
따라서 이에 대한 함수를 작성해 보겠습니다. -
예시
const arr = [45, 76, 54, 43, '|', 54, '|', 1, 66, '-', '|', 34, '|', 5, 76]; const getIndex = (arr, txt, n) => { const position = arr.reduce((acc, val, ind) => { if(val === txt){ if(acc.count+1 === n){ acc['index'] = ind; }; acc['count']++; } return acc; }, { index: -1, count: 0 }); return position.index; }; console.log(getIndex(arr, '|', 3)); console.log(getIndex(arr, 54, 2)); console.log(getIndex(arr, '-', 3));
출력
콘솔의 출력은 -
10 5 -1