본문 바로가기

TIL(today i learned)

[JS] map, ternary

오늘은 arry에서 map을 사용하는 방법에 대해 배웠다.

도, ternary operator도 사용해봤다.

 

MDN에서 정의하고 있는 map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

 

MDN에서 정의하고 있는 ternary operator

The conditional (ternary) operator  is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else
 statement.

 

아래블로그에 map에 대한 자세한 설명과 다양한 예제가 있어 이해하기 쉬웠다.

 

https://7942yongdae.tistory.com/entry/Javascript-Array-map-%EC%82%AC%EC%9A%A9%EB%B2%95


map을 이용하니 for 문을 사용하여 순회하던 것이 확 줄어들어 코드가 간결해지고, 두개의 배열을 동시에 처리할 수 있어서 유용했다.

 

아래는 위의 블로그에서 공부한 map을 활용하여

프로그래머스 Lv.1 성격 유형 검사하기

문제의 답으로 제출한 것

function solution(survey, choices) {
    var answer = '';
    let ans_obj = {
        'R':0,
        'T':0,
        'C':0,
        'F':0,
        'J':0,
        'M':0,
        'A':0,
        'N':0,
    }
    
    survey.map((value, i) => {
        if(choices[i] < 4) ans_obj[value.substring(0,1)] += 4-choices[i]
        if(choices[i] > 4) ans_obj[value.substring(1,2)] += choices[i] - 4 
    })
    
    ans_obj.R >= ans_obj.T ? answer +='R' : answer +='T';
    ans_obj.C >= ans_obj.F ? answer +='C' : answer +='F';
    ans_obj.J >= ans_obj.M ? answer +='J' : answer +='M';
    ans_obj.A >= ans_obj.N ? answer +='A' : answer +='N';
    return answer;
}