Set 객체는 모든 유형의 고유 값들의 집합(set)을 다루는 자료구조입니다.
이를 활용해 중복을 제거하고 고유한 값을 효과적으로 관리할 수 있습니다.
const set1 = new Set([1, 2, 3, 4, 5]);
const set2 = new Set([4, 5, 6, 7, 8]);
// 합집합(union)
const union = new Set([...set1, ...set2]);
console.log([...union]); // [1, 2, 3, 4, 5, 6, 7, 8]
// 교집합(intersection)
const intersection = new Set([...set1].filter((value) => set2.has(value)));
console.log([...intersection]); // [4, 5]
// 차집합(difference)
const difference = new Set([...set1].filter((value) => !set2.has(value)));
console.log([...difference]); // [1, 2, 3]
const numbers = [2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5];
console.log([...new Set(numbers)]); // [2, 13, 4, 5, 6, 7, 32]
// 대소문자 구문 (set은 "F"와 "f"를 모두 가지게 됨)
new Set("Firefox"); // Set(7) [ "F", "i", "r", "e", "f", "o", "x" ]
// 중복 문자열은 생략 ("f"는 문자열에서 2번 나타나기에, set은 하나만 가지게 됨)
new Set("firefox"); // Set(6) [ "f", "i", "r", "e", "o", "x" ]
※연관 게시물 : 🔗 [JavaScript 문법] Set