<aside> 💡
Set 객체는 중복되지 않는 유일한 값들의 집합이다. Set 객체는 배열과 유사하지만 다음과 같은 차이가 있다.
</aside>
Set 객체의 특성은 수학적 집합의 특성과 일치한다. Set은 수학적 집합을 구현하기 위한 자료구조다.
따라서 Set을 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있다.
Set 객체는 Set 생성자 함수로 생성한다. Set 생성자 함수에 인수를 전달하지 않으면 빈 Set 객체가 생성된다.
[ 예제 37 - 01 ]
const set = new Set();
console.log(set); // Set(0) {}
[ 예제 37 - 02 ]
const set1 = new Set([1,2,3,3]);
console.log(set1); // Set(3) {1,2,3}
const set2 = new Set('hello');
console.log(set2); // Set(4) {"h","e","l","o"}
[ 예제 37 - 03 ]
// 배열의 중복 요소 제거
const uniq = array => array.filter((v,i,self) => self.indexOf(v) === i);
console.log(uniq([2,1,2,3,4,3,4])); // [2,1,3,4]
// Set을 사용한 배열의 중복 요소 제거
const uniq = array => [ ...new Set(array)];
console.log(uniq([2,1,2,3,4,3,4])); // [2,1,3,4];
Set 객체의 요소 개수를 확인할 때는 Set.prototype.size 프로퍼티를 사용 !