본문 바로가기
자바스크립트

string 배열에서 중복이 있는지 확인하기 / 중복 제거하여 리턴하기

by 곰돌찌 2021. 10. 25.

string 배열에서 중복이 있는지 확인을 해야하는 작업이 필요해서 서치를 하다가

남겨두면 좋을 것 같아서 남겨보고자 한다.

 

const arry = ['hello', 'world', 'hello', 'bears', 'go', 'to', 'home'];

const findDuplicates = (arr) => {
	return arr.filter((item, index) => arr.indexOf(item) !== index);
}

const duplicates = findDuplicates(arry);
console.log(duplicates);

// Output: ['hello']

 

indexOf의 특징을 사용하는 것인데, indexOf는 배열에서 첫 번째로 찾아지는 데이터의 index의 값을 리턴하는데

중복되어있는 경우, Index값과 맞지 않기 때문에 어떤 중복이 있는지 체크할 수 있다.

 

그렇다면 중복제거된 배열만 찾으려면?

const arry = ['hello', 'world', 'hello', 'bears', 'go', 'to', 'home'];

const filterDuplicates = (arr) => {
	return arr.filter((item, index) => arr.indexOf(item) === index);
}

const filterArray = filterDuplicates(arry);
console.log(filterArray);

// Output: ['hello', 'world', 'bears', 'go', 'to', 'home']

 

이렇게 확인하면 된다!

댓글