[JavaScript] new Set()으로 배열에 중복이 있는지 확인하기

new Set([ iterable ])

Set()은 모든 값을 하나씩만 중복되지 않게 모아주는 Collection객체라고 한다.

let arr = [1,2,2,3,4,4,5];
let newCollection = new Set(arr);
let newArr = [...newCollection];

console.log(newCollection); //{1, 2, 3, 4, 5}
console.log(newArr); //[1, 2, 3, 4, 5]

if(arr.length !== newCollection.size) console.log('중복있음'); //중복있음

위의 예시처럼 arr.length와 newCollection.size를 비교하거나 Set()으로 만든 Collection객체를 다시 배열로 바꾸어 비교해 중복이 있는지 확인할 수 있다.