N개의 문자열이 입력되면 중복된 문자열은 제거하고 출력하는 프로그램을 작성하세요. 출력하는 문자열은 원래의 입력순서를 유지합니다.
▣ 입력설명
첫 줄에 자연수 N이 주어진다.(3<=N<=30)
두 번째 줄부터 N개의 문자열이 주어진다. 문자열의 길이는 100을 넘지 않습니다.
▣ 출력설명
첫 줄부터 중복이 제거된 문자열을 차례로 출력한다.
▣ 입력예제 1
5
good
time
good
time
student
▣ 출력예제 1
good
time
student
const input = `5
good
time
good
time
student`
.trim()
.split("\n");
const num = Number(input[0]);
const inputArr = input.splice(1, 5);
function solution(inputArr) {
let answer = [];
// filter => 해당 조건에 맞는 값 반환
inputArr.filter((item, i) => {
// indexOf => 해당 조건에 맞는 첫번째 값만 반환
if (inputArr.indexOf(item.trim()) === i) {
answer.push(item);
}
});
return answer;
}
처음에 includes 메서드를 사용해서 해결해보려 했다.
const input = `5
good
time
good
time
student`
.trim()
.split("\n");
const num = Number(input[0]);
const inputArr = input.splice(1, 5);
function solution(inputArr) {
let answer = [];
for (let i = 0; i < inputArr.length; i++) {
if (answer.includes(inputArr[i])) {
const indexNum = answer.indexOf(inputArr[i]);
answer.slice(indexNum);
} else {
answer.push(inputArr[i]);
}
}
return answer;
}
console.log(solution(inputArr));
하지만 이렇게 하면 가독성도 안좋을 뿐더러 답도 나오지 않았다.