Set & Map

공룡개발자·2022년 7월 25일
0
post-thumbnail

Set 객체

Set 객체는 중복되지 않는 값들의 집합으로, 배열과 유사하지만 인덱스와 순서가 없다.
또한 이터러블을 인수로 받아 Set 객체를 생성하며, 이터러블 내 중복된 값은 저장되지 않는다.

Set 객체가 없었을 때!

const set = arr => arr.filter((v, i, self) => self.indexOf(v) === i);

Set 용법

const set = new Set();

1. 개수 확인
set.size();

2. 추가
set.add(1);

3. 여부 확인
set.has(1); 

4. 삭제
set.delete(1);

5. 일괄 삭제
set.clear();

Set 객체는 이터러블이다. 즉, 순환이 가능하다. 순환가능한 배열에 사용가능한 for, forEach 사용이 가능하고, 스프레드 문법, 구조분해할당 역시 가능하다. 추가로 Set 객체가 요소의 순서를 보장하지 않지만 추가된 순서를 따른다. 이는 다른 이터러블과의 호환성을 유지하기 위함이다.

Set의 집합 연산

Set을 통해 교집합, 합집합, 차집합을 구현할 수 있다.

const set_a = new Set([1, 2, 3, 4]);
const set_b = new Set([2, 4]);

1. 교집합
console.log(set_a.intersection(set_b)); >> Set(2) {2, 4}
or
console.log(new Set([...set_a].filter(v => set_b.has(v)))

2. 합집합
console.log(set_a.union(set_b)); >> Set(4) {1, 2, 3, 4}
console.log(new Set([...set_a, ...set_b]))

3. 차집합
console.log(set_a.difference(set_b)); >> Set(2) {1, 3}
console.log(new Set([...set_a].filter(v => !set_b.has(v)))

4. 상위집합(set_a가 set_b의 상위 집합인가)
console.log(set_a.isSuperset(set_b)); >> true

Map 객체

Map 객체는 키와 값으로 이뤄졌다는 면에서 객체와 유사하지만, 객체와 달리 Map 객체는 js의 모든 값을 키로 삼을 수 있고, 이터러블하다는 면에서 객체와 차이를 지닌다.

Map 용법

const map = new Map();

1. 개수 확인
map.size();

2. 추가
map.set(1);

3. 여부 확인
map.has(1); 

4. 삭제
map.delete(1);

5. 일괄 삭제
map.clear();

6. 순회
map.forEach((value, key) => {
  console.log(key, value);
}
console.log(map.keys());
console.log(map.values());
console.log(map.entries());     

모던 자바스크립트 Deep Dive를 읽고 작성한 글입니다.

profile
공룡의 발자취

0개의 댓글