소문자로 된 한개의 문자열이 입력되면 중복된 문자를 제거하고 출력하는 프로그램을 작성하세요.
제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다.
function solution(s){
let answer="";
for(let x of s) {
if(answer.indexOf(x) === -1) answer += x;
}
return answer;
}
console.log(solution("ksekkset"));
function solution(s){
let answer="";
for(let i=0; i<s.length; i++){
if(s.indexOf(s[i])===i) answer+=s[i];
}
return answer;
}
console.log(solution("ksekkset"));
N개의 문자열이 입력되면 중복된 문자열은 제거하고 출력하는 프로그램을 작성하세요. 출력하는 문자열은 원래의 입력순서를 유지합니다.
function solution(s){
let answer = [];
for(let x of s) {
if(answer.indexOf(x) === -1) answer.push(x);
}
return answer;
}
let str=["good", "time", "good", "time", "student"];
console.log(solution(str));
function solution(s){
let answer;
answer=s.filter((v, i)=>{
if(s.indexOf(v)===i) return v;
});
return answer;
}
let str=["good", "time", "good", "time", "student"];
console.log(solution(str));
filter()
메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
정답 풀이에서는 s
의 각 요소를 v
로, 처리할 현재 요소의 index
를 i
로 사용하여, s.indexOf(v)
를 통해 s
에서 v
가 처음으로 등장하는 경우의 index
와 현재 index
가 같은 경우 answer
에 포함되도록 하였고, 그에 따른 결과를 return
하도록 하였다. 참고하자.