개발 공부/알고리즘

[프로그래머스 알고리즘] "서울에서 김서방 찾기" JavaScript / find, findIndex, indexOf

U_D 2022. 3. 14. 09:53

1. 문제 설명

String형 배열 seoul의 element중 "Kim"의 위치 x를 찾아, "김서방은 x에 있다"는 String을 반환하는 함수, solution을 완성하세요. seoul에 "Kim"은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.

 

 

2. 제한 조건

seoul은 길이 1 이상, 1000 이하인 배열입니다.
seoul의 원소는 길이 1 이상, 20 이하인 문자열입니다.
"Kim"은 반드시 seoul 안에 포함되어 있습니다.

 

 

 

 

3. 예시

입력/출력

 

4. 풀이

[indexOf 활용]

배열 내장함수의 위치를 아는 방법을 검색해서 indexOf를 찾아서 한번에 성공!

function solution(seoul) {
    var answer = '';
        where = seoul.indexOf("Kim")
        answer = `김서방은 ${where}에 있다`
    return answer;
}

 

[배열 검색 메서드]

 

  • 자바스크립트 Array.prototype
  • 배열에서 원하는 값 또는 식별자를 찾아내는 메서드
  • 배열을 순차 반복
  • find 는 인자로 받은 판별 함수를 만족하는 첫 번째 요소를 반환
  • findIndex 는 인자로 받은 판별 함수를 만족하는 첫 번째 식별자를 반환
  • indexOf 는 인자로 요소를 받아 만족하는 첫 번째 식별자를 반환
  • element : 배열 내 값 / index : 배열내 몇번째인지

 

.find (element, index, array) : 판별 함수를 만족하는 첫 요소를 반환 (배열 내 값)

 

  • arr.find(callback)
  • 반환 타입은 찾은 요소의 타입, 없다면 undefinded
  • callback(element, index, array) → 콜백 함수가 받는 인자(각 인자는 find 메서드를 호출한 배열에서 받아옴)
  • 원하는 요소 찾기
  • 원하는 요소를 찾자마자 메서드를 종료함(뒤쪽 요소는 관심조차 주지도 않는다)
const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find1 = arr.find((element, index, array) => {
    // 인덱스 2인 요소를 찾을 때 까지 반복
    console.log('콜백함수를 실행한 배열은? ', array);
    return index == 2;
});
const find2 = arr.find((element, index, arr) => element === 3);
const find3 = arr.find((e) => e > 8);
const find4 = arr.find((e) => e > 10);

console.log('find1:', find1);
console.log('find2:', find2);
console.log('find3:', find3);
console.log('find4:', find4);
콜백함수를 실행한 배열은?  [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3]
콜백함수를 실행한 배열은?  [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3]
콜백함수를 실행한 배열은?  [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3]
find1: 9
find2: 3
find3: 9
find4: undefined



.findIndex (element, index, array) : 판별 함수를 만족하는 첫 식별자 반환 (배열 내 몇번째인지)

 

 

  • arr.findIndex(callback)
  • 반환 타입 number, 없다면 -1
  • callback(element, index, array) → 콜백함수가 받는 인자(각 인자는 findIndex 메서드를 호출한 배열에서 받아옴)
  • 원하는 요소의 식별자 찾기
  • 원하는 요소를 찾자마자 메서드를 종료함
const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find1 = arr.findIndex((element, index, array) => {
    return index < 7 && index > 5;
});
const find2 = arr.findIndex((element, index, arr) => element === 3);
const find3 = arr.findIndex((e) => e > 8);
const find4 = arr.findIndex((e) => e > 10);

console.log('findIndex1:', find1);
console.log('findIndex2:', find2);
console.log('findIndex3:', find3);
console.log('findIndex4:', find4);
findIndex1: 6
findIndex2: 5
findIndex3: 2
findIndex4: -1


.indexOf (element, index, array) : 인자로 받은 값을 찾아 맞는 식별자 반환 (찾고자 하는 값이 몇번째인지)

 

  • arr.indexOf(search, fromIndex)
  • 반환 타입 number, 없다면 -1
  • search 매개변수는 배열에서 찾을 요소를 받음
  • 원하는 요소의 식별자 찾기
  • 원하는 요소를 찾자마자 메서드를 종료함
const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find1 = arr.indexOf(1);
const find2 = arr.indexOf(2);
const find3 = arr.indexOf(3);
const find4 = arr.indexOf(4);

console.log('findIndex1:', find1);
console.log('findIndex2:', find2);
console.log('findIndex3:', find3);
console.log('findIndex4:', find4);
findIndex1: 3
findIndex2: 6
findIndex3: 5
findIndex4: 11

출처 : https://bbaktaeho-95.tistory.com/40