[프로그래머스 | Javascript] 코딩테스트 입문 - 영어가 싫어요

박기영·2022년 11월 8일
0

프로그래머스

목록 보기
78/126

solution

function solution(numbers) {
    const stringNumber = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];

    stringNumber.forEach((item, index) => {
        numbers = numbers.split(item).join(String(index));
    })
    
    return Number(numbers);
}

후보로 주어진 문자열들을 하드 코딩했다.
zero의 인덱스는 0, one의 인덱스는 1... 이 점을 활용하여
split()join()을 활용해서 문자열을 계속해서 분리하고 합치기를 반복했다.

즉, 아래와 같은 구조로 코드가 돌아가는 것이다.

const splited = "onetwothreefour".split("one"); // ["", "twothreefour"]
const joined = splited.join("1"); // "1twothreefour"
profile
나를 믿는 사람들을, 실망시키지 않도록

0개의 댓글