JavaScript에서 Set은 유일한 원시 값이나 객체 참조만 담을 수 있는, 배열과 비슷한 자료 구조예요.
Set은 반드시 Set 생성자를 사용해 만들어야 해요. 생성자에 배열을 넘겨서 초기값을 지정할 수 있어요.
const emptySet = new Set();
const setWithInitialValues = new Set(['hello', 'world']);
어떤 값이 Set의 원소 중 하나와 엄격하게 같으면, 그 값은 Set에 추가할 수 없어요.
const set = new Set();
set.add(10);
set.add(10); // 10 is strictly equal to 10, so it can't be added again
set.size;
//=> 1;
set.has(10);
//=> true
set.delete(10);
//=> true; 10 was removed
set.delete(10);
//=> false; 10 is not in the set, so nothing happened
const obj = { color: 'magenta' };
const eerilySimilarObj = { color: 'magenta' };
set.add(obj);
set.add(eerilySimilarObj); // obj and eerilySimilarObj reference different objects, so they can both be added
set.size;
//=> 2
set.clear();
set.size;
//=> 0
배열은 Set 생성자를 사용해 Set으로 변환해요. Set은 스프레드 문법이나 Array.from()을 사용해 배열로 변환할 수 있어요.
const arrayWithDuplicates = [7, 3, 3, 9, 3];
const arrayWithoutDuplicates = [...new Set(arrayWithDuplicates)]; // [7, 3, 9]
const anotherArrayWithoutDuplicates = Array.from(new Set(arrayWithDuplicates)); // [7, 3, 9]
Set은 키 기반 컬렉션이라서, 원소가 키로 인덱싱되고 삽입 순서대로 반복할 수 있어요. Set 원소의 _키_와 _값_은 같기 때문에 Set.keys()와 Set.values()는 서로 바꿔 쓸 수 있어요.
const apples = ['Granny Smith', 'Honey Crisp', 'Royal Gala'];
const appleSet = new Set(apples);
for (let apple of appleSet.keys()) {
console.log(apple);
}
// 'Granny Smith'
// 'Honey Crisp'
// 'Royal Gala'
for (let apple of appleSet.values()) {
console.log(apple);
}
// 'Granny Smith'
// 'Honey Crisp'
// 'Royal Gala'
for (let apple of appleSet.entries()) {
console.log(apple);
}
// ['Granny Smith', 'Granny Smith']
// ['Honey Crisp', 'Honey Crisp']
// ['Royal Gala', 'Royal Gala']
데이터 모음을 저장할 때 배열 대신 Set을 고르는 이유는 보통 저장할 값들이 유일해야 하기 때문이에요. 그런데 배열로도 유일성을 강제할 수 있으니, 왜 그런지 잘 와닿지 않을 수 있어요.
간단히 말하면, Set은 검색에 최적화되어 있고 배열은 그렇지 않기 때문이에요. Array.indexOf() 같은 배열 검색 메서드는 실행 시간이 배열 크기에 비례해 늘어나요. 즉, 배열에 원소가 많을수록 검색하는 데 시간이 더 오래 걸려요. 반면 Set의 검색 메서드는 실행 시간이 일정해서, Set의 크기와 상관없이 항상 같아요.
다만 실제로는, 데이터가 아주 많지 않은 이상 이 성능 차이는 거의 느낄 수 없어요.