[JavaScript] 로또 최고/최저 순위 맞추기

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

JavaScript

목록 보기
3/14
post-thumbnail
function solution(lottos, win_nums) {
    
    let matchnum = 0;
    let zeroCnt = 0;
    const answer = [6,6,5,4,3,2,1];
    
    for(let i=0; i<lottos.length; i++){
        if(lottos[i] === 0){
            zeroCnt += 1;
        }
    }
    
    for(let i=0; i<lottos.length; i++){
        for(let j=0;  j<win_nums.length; j++){
            if( lottos[i] === win_nums[j]){
                matchnum +=1;
            }
        }
    }
    const High = zeroCnt===6 ? 1 : answer[matchnum+zeroCnt]; 
    const Low = answer[matchnum];

    
    
    return [High, Low];
}

일일히 for문으로 계산해줬는데 더 좋은 방법이 있었다.

일단 for문을 쓸 때 처음에

for( const num in lotts )라고 했는데 이건 완전히 잘못된 방식이었다.
for in 문은 객체를 배열로 나타낼 때 사용하는 거여서 정수배열로 들어오는 lottos에는 맞지 않는 문법!

다음은.. 아주 유용한 js문법

  1. array.filter((e)=>e===0).length 로 lottos에 0의 갯수를 바로 계산가능하다는 것....!

  2. arr.filter((e)=>lottos.includes(e)).length 로 lottos에 포함 된 것중 arr에 있는 갯수도 바로 계산가능..

좋은 문법들이 많은데 내가 몰라서 너무 1차원적인 코딩을 하고 있는 것 같구만! 다음에 꼭 써먹어주고 만다~~~!!

profile
Keep going and level up !

0개의 댓글