Oops, All Code!/🤯 Oops, My Algorithm!

♡̈ 15. 프로그래머스:: 서울에서 김 서방 찾기

밍동망동 2024. 7. 12. 13:41

 

어떻게 찾아야하나 고민했는데, 생각해보니 index 값만 뽑으면 되는 문제였다.

indexOf 메서드를 사용해 쉽게 해결할 수 있었다.

 

indexOf라는 메서드를 떠올리기만 하면 손쉽게 풀 수 있었기 때문에,

기본입출력 문제인 0단계에서 크게 벗어나지 않은 문제 같은데

1단계에 속해있는게 신기했다.

function solution(seoul) {
    const index = seoul.indexOf("Kim");
    
    return `김서방은 ${index}에 있다`;
}

 

다른 사람의 코드를 살펴보던 중, findIndex의 존재에 대해 알았다.

 

Array.prototype.findIndex() - JavaScript | MDN

The findIndex() method of Array instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

developer.mozilla.org

 

findIndex는 판별 함수를 만족할 때 첫 번째 인덱스를 반환한다.

더 복잡한 조건을 가진 경우도 식을 만들 수 있기 때문에,

해당 경우에서는 덜 적합한 것 같다.

const index = seoul.findIndex(element => element === "Kim");

indexOf와 findIndex

 

  indexOf findIndex
용도 배열에서 특정 값 검색 배열에서 조건 만족하는 요소의 인덱스 검색
인수 검색할 값 판별 함수(callback)
적합 단순 값 검색 복잡한 조건 검색