[JavaScript] 모의고사

똔의 기록·2022년 5월 13일
0

JavaScript

목록 보기
4/14
post-thumbnail
function solution(answers) {
    var answer = [];
    const first =[1,2,3,4,5];
    const second =[2,1,2,3,2,4,2,5];
    const third =[3,3,1,1,2,2,4,4,5,5];
    
    const checkScore = [];
    let firstNum =0;
    let secondNum =0;
    let thirdNum =0;
    
    for(let i =0; i<answers.length; i++){
        if( answers[i] === first[i%5]){
            firstNum +=1;
        }
        if(answers[i] === second[i%8]){
            secondNum+=1;
        }
        if(answers[i] === third[i%10]){
            thirdNum+=1;
        }
    }
    checkScore[0] = firstNum;
    checkScore[1] = secondNum;
    checkScore[2] = thirdNum;
    
    const maxScore = Math.max(...checkScore);
    for(let i=0; i<3; i++){
        if(checkScore[i]===maxScore) answer.push(i+1);
    }
    
    return answer;
}

여기서 내가 처음 알게된 자바스크립트 문법은

Math.max(...checkScore)!
스프레드 연산자로 가장 큰 수를 쉽게 얻을 수 있다.

하지만 더 정확한 코드를 짜려면 reduce를 사용하여 하는게 좋다고 한다.

var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
}, -Infinity);
profile
Keep going and level up !

0개의 댓글