코딩테스트 by JS

JavaScript<중복단어제거>

mickey7 2023. 3. 15. 01:23

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

 

  • 중복 문자 제거에서 사용한 indexOf메소드 활용! --> 문자뿐만 아니라 배열에서도 활용 가능.

filter() 메소드 활용한 풀이
 
<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){
                let answer;
                answer = s.filter(function(value,index){
                    console.log(s.indexOf(s[index]),index);
                    
                    if(s.indexOf(s[index])===index) return true;  
                })
                return answer;
                
            }
            let str=["good", "time", "good", "time", "student"];
            console.log(solution(str));
        </script>
    </body>
</html>
 

Array.prototype.filter() - JavaScript | MDN

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

developer.mozilla.org

  • filter 메소드로 콜백함수 안에서 true 값으로 나온 요소들만 골라서 새로운 배열을 만들 수 있다.
  • filter(v,i)함수 안에 매개변수로 배열 값(v)과, 인덱스(i) 사용 가능! + 내부말고 외부에도 함수 만들어서 콜백함수로 활용할 수도 있음.
  • filter 함수 안에 화살표 함수도 가능하긴 한데 내가 아직 활용법을 잘 몰라서..
  • 고차 함수란, 함수를 파라미터로 전달받거나 연산의 결과로 반환해주는 메서드를 일컫는다고 한다. --> filter() 함수는 안에 매개변수로 함수를 넣을 수 있으니 고차 함수!