중복 단어 제거

지창언·2022년 7월 24일

codingTest

목록 보기
14/29

Index

1.문제
2.내 코드


문제

여러 단어를 가진 배열을 입력받아, 중복되지 않은 단어로만 구성하여 배열을 반환하시오.


내 코드

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){  
                let answer =[];
                s.filter((ele,idx)=>{
                    if(answer.indexOf(ele)==-1){
                        answer.push(ele);
                    }
                })
                return answer;
            }
            let str=["good", "time", "good", "time", "student"];
            console.log(solution(str));
        </script>
    </body>
</html>

위 코드는 filter()함수와 indexOf()를 이용한다.
filter 함수를 통해 입력 배열을 돌면서 answer에 안들어있는 요소만 answer에 집어넣도록 한다.


profile
프론트엔드 개발자가 되고 싶은...

0개의 댓글