0%

Set 과 Map

1. Set

Set 객체는 중복되지 않는 유일한 값들의 집합(set)이다. Set 객체는 배열과 유사하지만 아래와 같은 점에서 차이가 있다.

구분 배열 Set 객체
동일한 값을 중복하여 포함
요소 순서의 의미
인덱스로 요소에 접근

이러한 Set 객체의 특성은 수학적 집합의 특성과 일치한다. Set은 수학적 집합을 구현하기 위한 자료 구조이다. Set을 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있다.

1.1. Set 객체의 생성

Set 객체는 Set 생성자 함수로 생성한다. Set 생성자 함수에 인수를 전달하지 않으면 빈 Set 객체가 생성된다.

1
2
const set = new Set();
console.log(set); // Set(0) {}

Set 생성자 함수는 이터러블을 인수로 전달받아 Set 객체를 생성한다. 이때 이터러블의 중복된 값은 Set 객체에 요소로 저장되지 않는다.

1
2
3
4
5
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"}

중복을 허용하지 않는 Set 객체의 특성을 활용하여 배열에서 중복된 요소를 제거할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
// 배열의 중복 요소 제거
function uniq(array) {
return array.filter((v, i, self) => self.indexOf(v) === i);
}
console.log(uniq([2, 1, 2, 3, 4, 3, 4])); // [2, 1, 3, 4]

// Set을 사용한 배열의 중복 요소 제거
function uniq(array) {
return [...new Set(array)];
}
console.log(uniq([2, 1, 2, 3, 4, 3, 4])); // [2, 1, 3, 4]

1.2. 요소 개수 확인

Set 객체의 요소 개수를 확인할 때는 Set.prototype.size 프로퍼티를 사용한다.

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

console.log(set); // Set(3) {1, 2, 3}
console.log(set.size); // 3

Set.prototype.size 프로퍼티는 setter 함수없이 getter 함수만 존재하는 접근자 프로퍼티이다. 따라서 Set.prototype.size 프로퍼티에 숫자를 할당하여 Set 객체의 요소 개수를 변경할 수 없다.

1
2
3
4
5
6
7
const set = new Set([1, 2, 3]);

console.log(Object.getOwnPropertyDescriptor(Set.prototype, 'size'));
// {set: undefined, enumerable: false, configurable: true, get: ƒ}

set.size = 10; // 무시된다.
console.log(set.size); // 3

1.3. 요소 추가

Set 객체에 요소를 추가할 때는 Set.prototype.add 메소드를 사용한다.

1
2
3
4
5
const set = new Set();
console.log(set); // Set(0) {}

set.add(1);
console.log(set); // Set(1) {1}

Set.prototype.add 메소드는 새로운 요소가 추가된 Set 객체를 반환한다. 따라서 연속적으로 Set.prototype.add 메소드를 호출할 수 있다.

1
2
3
4
const set = new Set();

set.add(1).add(2);
console.log(set); // Set(2) {1, 2}

Set 객체에 중복된 요소의 추가는 허용되지 않는다. 단, 이때 에러가 발생하지는 않고 무시된다.

1
2
3
4
const set = new Set();

set.add(1).add(2).add(2);
console.log(set); // Set(2) {1, 2}

일치 비교 연산자 ===을 사용하면 NaN과 NaN을 다르다고 평가한다.(“7.3.1. 동등/일치 비교 연산자” 참고) 하지만 Set 객체는 NaN과 NaN을 같다고 평가하여 중복 추가를 허용하지 않는다. 또한 일치 비교 연산자 ===와 마찬가지로 +0과 -0도 같다고 평가하여 중복 추가를 허용하지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
const set = new Set();

console.log(NaN === NaN); // false
console.log(0 === -0); // true

// NaN과 NaN을 같다고 평가하여 중복 추가를 허용하지 않는다.
set.add(NaN).add(NaN);
console.log(set); // Set(1) {NaN}

// +0과 -0을 같다고 평가하여 중복 추가를 허용하지 않는다.
set.add(0).add(-0);
console.log(set); // Set(2) {NaN, 0}

Set 객체는 자바스크립트의 모든 값을 요소로 저장할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
const set = new Set();

set
.add(1)
.add('a')
.add(true)
.add(undefined)
.add(null)
.add({})
.add([]);
console.log(set); // Set(7) {1, "a", true, undefined, null, {}, []}

1.4. 요소 존재 여부 확인

Set 객체에 특정 요소가 존재하는지 확인하려면 Set.prototype.has 메소드를 사용한다.

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

console.log(set.has(2)); // true
console.log(set.has(4)); // false

1.5. 요소 삭제

Set 객체의 요소를 삭제할 때는 Set.prototype.delete 메소드를 사용한다.

1
2
3
4
5
6
7
8
9
const set = new Set([1, 2, 3]);

// 요소 2를 삭제한다.
set.delete(2);
console.log(set); // Set(2) {1, 3}

// 요소 1을 삭제한다.
set.delete(1);
console.log(set); // Set(1) {3}

Set.prototype.delete 메소드에는 인덱스가 아니라 삭제하려는 요소값을 전달하여야 한다. Set 객체는 순서에 의미가 없다. 다시 말해 배열과 같이 인덱스를 갖지 않는다.

만약 존재하지 않는 Set 객체의 요소를 삭제하려하면 에러없이 무시된다.

1
2
3
4
5
const set = new Set([1, 2, 3]);

// 존재하지 않는 요소 0를 삭제한다.
set.delete(0); // 무시된다
console.log(set); // Set(3) {1, 2, 3}

Set.prototype.delete 메소드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다. 따라서 Set.prototype.add 메소드와 같이 연속적으로 호출할 수 없다.

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

// delete는 불리언 값을 반환한다.
set.delete(1).delete(2); // TypeError: set.delete(...).delete is not a function

1.6. 요소 일괄 삭제

Set 객체의 요소를 일괄 삭제할 때는 Set.prototype.clear 메소드를 사용한다.

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

set.clear();
console.log(set); // Set(0) {}

1.7. 요소 순회

Set 객체의 요소를 순회할 때는 Set.prototype.forEach 메소드를 사용한다. Set.prototype.forEach 메소드는 Array.prototype.forEach 메소드와 유사하게 콜백함수와 forEach 메소드 내부에서 this로 사용될 객체(옵션)를 전달한다. 이때 콜백함수는 아래와 같이 3개의 인수를 전달받는디.

  • 첫번재 인수 : 현재 순회중인 요소값
  • 두번재 인수 : 현재 순회중인 요소값
  • 세번재 인수 : 현재 순회중인 Set 객체(this)

첫번재 인수와 두번재 인수는 같은 값이다. 이처럼 동작하는 이유는 Array.prototype.forEach 메소드와 인터페이스를 통일하기 위함으로 다른 의미는 없다.

1
2
3
4
5
6
7
8
const set = new Set([1, 2, 3]);

set.forEach((v, v2, set) => console.log(v, v2, set));
/*
1 1 Set(3) {1, 2, 3}
2 2 Set(3) {1, 2, 3}
3 3 Set(3) {1, 2, 3}
*/

Set 객체는 이터러블이다. 따라서 for…of문으로 순회할 수 있으며 스프레드 문법의 대상이 될 수도 있다.

1
2
3
4
5
6
7
8
9
10
11
12
const set = new Set([1, 2, 3]);

// Set 객체는 Set.prototype의 Symbol.iterator 메소드를 상속받는 이터러블이다.
console.log(Symbol.iterator in set); // true

// 이터러블인 Set 객체는 for...of 문으로 순회할 수 있다.
for (const value of set) {
console.log(value); // 1 2 3
}

// 이터러블인 Set 객체는 스프레드 문법의 대상이 될 수 있다.
console.log([...set]); // [1, 2, 3]

Set 객체는 요소의 순서에 의미를 갖지 않지만 Set 객체를 순회하는 순서는 요소가 추가된 순서를 따른다. 이는 ECMAScript 사양에 규정되어 있지는 않지만 다른 이터러블의 순회와 호환성을 유지하기 위함이다.

1.8. 집합 연산

Set은 수학적 집합을 구현하기 위한 자료 구조이다. Set을 통해 교집합, 합집합, 차집합 등을 구현할 수 있다. 이들 프로토타입 메소드를 구현하면 아래와 같다.

1.8.1. 교집합

교집합(A∩B)은 집합 A와 집합 B의 공통 요소로 구성된다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Set.prototype.intersection = function (set) {
const result = new Set();

for (const value of set) {
// 2개의 set의 요소가 공통되는 요소이면 교집합의 대상이다.
if (this.has(value)) result.add(value);
}

return result;
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA와 setB의 교집합
console.log(setA.intersection(setB)); // Set(2) {2, 4}
// setB와 setA의 교집합
console.log(setB.intersection(setA)); // Set(2) {2, 4}

또는 아래와 같은 방법으로도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
Set.prototype.intersection = function (set) {
return new Set([...this].filter(v => set.has(v)));
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA와 setB의 교집합
console.log(setA.intersection(setB)); // Set(2) {2, 4}
// setB와 setA의 교집합
console.log(setB.intersection(setA)); // Set(2) {2, 4}

1.8.2. 합집합

합집합(A∪B)은 집합 A와 집합 B의 중복없는 모든 요소로 구성된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Set.prototype.union = function (set) {
// this(Set 객체)를 복사
const result = new Set(this);

for (const value of set) {
// 합집합은 2개의 Set 객체의 모든 요소로 구성된 집합이다. 중복된 요소는 포함되지 않는다.
result.add(value);
}

return result;
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA와 setB의 합집합
console.log(setA.union(setB)); // Set(4) {1, 2, 3, 4}
// setB와 setA의 합집합
console.log(setB.union(setA)); // Set(4) {2, 4, 1, 3}

또는 아래와 같은 방법으로도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
Set.prototype.union = function (set) {
return new Set([...this, ...set]);
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA와 setB의 합집합
console.log(setA.union(setB)); // Set(4) {1, 2, 3, 4}
// setB와 setA의 합집합
console.log(setB.union(setA)); // Set(4) {2, 4, 1, 3}

1.8.3. 차집합

차집합(A-B)은 집합 A에는 존재하지만 집합 B에는 존재하지 않는 요소들의 집합이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Set.prototype.difference = function (set) {
// this(Set 객체)를 복사
const result = new Set(this);

for (const value of set) {
// 차집합은 어느 한쪽 집합에는 존재하지만 다른 한쪽 집합에는 존재하지 않는 요소로 구성된 집합이다.
result.delete(value);
}

return result;
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA에 대한 setB의 차집합
console.log(setA.difference(setB)); // Set(2) {1, 3}
// setB에 대한 setA의 차집합
console.log(setB.difference(setA)); // Set(0) {}

또는 아래와 같은 방법으로도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
Set.prototype.difference = function (set) {
return new Set([...this].filter(v => !set.has(v)));
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA에 대한 setB의 차집합
console.log(setA.difference(setB)); // Set(2) {1, 3}
// setB에 대한 setA의 차집합
console.log(setB.difference(setA)); // Set(0) {}

1.8.4. 부분 집합과 상위 집합

집합 A가 집합 B에 포함되는 경우(A⊆B), 집합 A는 집합 B의 부분 집합이며 집합 B는 집합 A의 상위 집합이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// this가 subset의 상위 집합인지 확인한다.
Set.prototype.isSuperset = function (subset) {
for (const value of subset) {
// superset의 모든 요소가 subset의 모든 요소를 포함하는지 확인
if (!this.has(value)) return false;
}

return true;
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA가 setB의 상위 집합인지 확인한다.
console.log(setA.isSuperset(setB)); // true
// setB가 setA의 상위 집합인지 확인한다.
console.log(setB.isSuperset(setA)); // false

또는 아래와 같은 방법으로도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// this가 subset의 상위 집합인지 확인한다.
Set.prototype.isSuperset = function (subset) {
const supersetArr = [...this];
return [...subset].every(v => supersetArr.includes(v));
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 4]);

// setA가 setB의 상위 집합인지 확인한다.
console.log(setA.isSuperset(setB)); // true
// setB가 setA의 상위 집합인지 확인한다.
console.log(setB.isSuperset(setA)); // false

2. Map

Map 객체는 키와 쌍으로 이루어진 컬렉션이다. Map객체는 객체와 유사하지만 다음과같은 차이점이 있다.

구분 객체 Map객체
키로 사용할수있는 값 문자열 또는 심볼 값 객체를 포함하는 모든 값
이터러블 X O
크기확인 Object.keys(obj).length map.size

2.1 Map 객체의 생성

Map 객체는 Map 생성자 함수로 생성한다. Map 생성자 함수에 인수를 전달하지않으면 빈 Map객체가 생성된다.

1
2
const map = new Map();
console.log(map) // Map(0) {}

Map 생성자 함수는 이터러블을 인수로 전달 받아 Map객체를 생성한다. 이때 인수로 전달 되는 이터러블은 키와 값의 쌍으로 이루어진 요소로 구성이 되어야한다.

1
2
3
4
5
const map1 = new Map([['key1','value1'],['key1','value2']]);
console.log(map1) //Map(2) {'lkey1=>'value'm'key2'=>'value2'};

const map2 = new Map([1,2]);
// TypeError: Iterator value 1 is not an entry object

중복된 키는 Map 객체의 요소로 저장되지 않는다.

1
2
const map = new Map([['key1','value2'],['key1','value2']]);
console.log(map); // Map(1) {"key1" => "value1"}

2.2 요소의 개수확인

Map 객체의 요소의 개수 확인 할때에는 Map.prototype.size 프로퍼티를 사용한다.

1
2
3
const map = new Map([['key1','value1'],['key2','value2']]);
console.log(map); // Map(2) {"key1" => "value1", "key2" => "value2"}
console.log(map.size) //2

Map.prototype.size 프로퍼티는 setter함수 없이 getter함수만 존재하는 접그자 프로퍼티 이다. 따라서 Map.prototype.size 프로퍼티에 숫자를 할당하여 Map 객체의 요소개수를 변경 할 수 없다.

1
2
3
4
5
6
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
console.log(Object.getOwnPropertyDescriptor(Map.prototype,'size'));
//{set:undefined, enumberable:false,configurable:true,get:function}

map.size =10; //무시된다.
console.log(map.size) //2

2.3 요소 추가

Map 객체의 요소를 추가할 때는 Map.prototype.set메소드를 사용한다.

1
2
3
4
5
const map = new Map();
console.log(map) //Map(0) {};

map.set('key1','value1');
console.log(map) //Map(1) {'key1'=>'value1'};

Map.prototype.set메소드는 새로운 요소가 추가된 Map객체를 반환한다. 따라서 연속적으로 Map.prototype.set 메소드를 호출할 수 있다.

1
2
3
4
const map = new Map();
map.set('key1','value1')
.set('key2','value2');
console.log(map) // Map(2) {'key1'=>'value1','key2'=>'value2'};

Map객체에 중복된 키를 갖는 요소의 추가는 허용되지않는다. 단 이때 에러가 발생하지는 않고 무시된다.

1
2
3
4
5
const map = new Map();
map
.set('key1', 'value1')
.set('key1', 'value2');
console.log(map); // Map(1) {"key1" => "value1"}

객체는 문자열 또는 심볼 값만을 키로 사용할수 있지만 Map객체의 키 타입에는 제한이 없다. 따라서 객체는 포함한 모든 값을 키로 사용할 수 있다. 이는 Map 객체와 일반 객체의 가장 두드러지는 차이이다.

1
2
3
4
5
6
7
const map = new Map();
const lee = {name:'lee'};
const kim = {name:'kim'};

map.set(lee,'developer')
.set(kim,'developer');
console.log(map) // Map(2) { {name:'lee'}=> 'developer',{name:'kim'}=>'developer' };

2.4 요소 취득

Map객체의 요소를 취득 할때 는 Map.prototype.get메소드를 사용한다. Map객체에 해당하는 ㅣ를 갖는 요소가 존재하지 않으면 undefined을 반환한다.

1
2
3
4
5
6
7
8
const map = new Map();

const lee ={name:'lee'};
const kim ={name:'kim'};

map.set(lee,'deveoper').set(kim,'developer');
console.log(map.get(lee)); ///developer;
console.log(map.get('key')) //undefined

2.5 요소 존재 여부 확인

Map객체에 특정 요소가 존재하는지 확인 하려면 Map.prototype.has메소드를 사용한다.

1
2
3
4
5
6
7
const lee = {name:'lee'};
const kim ={name:'kim'};

const map = new Map([[lee,'developer'],[kim,'designer']]);

console.log(map.has(lee)) //true;
console.log(map.has('key')) //false

2.6 요소의 삭제

Map객체의 요소를 삭제할때에는 Map.prototype.delete메소드를 사용한다. 만약 존재하지 않는 Map객체의 요소를 삭제 하려면 에러없이 무시된다.

1
2
3
4
5
6
7
const lee = {name:'lee'};
const kim ={name:'kim'};

const map = new Map([[lee,'developer'],[kim,'designer']]);

map.delete(kim);
console.log(map) // Map(1) {{name:'lee'}=>'developer'};

Map.prototype.delete 메소드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다. 따라서 Map.prototype.set 메소드와 같이 연속적으로 호출 할수없다.

1
2
3
4
5
6
const lee ={name:'lee'};
const kim={name:'kim'};

const map = new Map([lee,'developer'],[kim,'designer']);

map.delete(lee).delete(kim) //TypeError: map.delete(...).delete is not a function

2.7 요소의 일괄 삭제

Map 객체의 요소를 일괄 삭제 할때는 Map.prototype.clear 메소드를 사용한다.

1
2
3
4
5
6
const lee ={name:'lee'};
const kim={name:'kim'};

const map = new Map([[lee,'developer'],[kim,'designer']]);
map.clear();
consoleg.log(map) //Map(0) {}

2.8 요소의 순회

Map 객체의 요서를 순회할 때는 Map.prototype.forEach메소드를 사용한다. Map.prototype.forEach메소드는 Array.prototype.forEach메소드와 유사하게 콜백함수와 forEach 메소드 내부에서 this로 사용 될 객체(옵션)를 전달한다. 이때 콜백 함수는 다음과 다팅 3개의 인수를 받는다.

  • 첫번째 인수 : 현재 순회중인 요소 값
  • 두번째 인수 : 현재 순회중인 요소 키
  • 세번째 인수 : 현재 순회중인 Map객체(this)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const lee = {name:'lee'};
const kim ={name:'kim'};

const map = new Map([[lee,'developer'],[kim,'designer']]);

map.forEach((v,k,map)=>consoel.log(v,k,map));
/*
developer {name: "Lee"} Map(2) {
{name: "Lee"} => "developer",
{name: "Kim"} => "designer"
}
designer {name: "Kim"} Map(2) {
{name: "Lee"} => "developer",
{name: "Kim"} => "designer"
}
*/

Map객체는 이터러블이다 .따라서 for …of문으로 순회할수있으며 스프레드 문법의 대상이 될 수 도있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const lee ={name:'lee'};
const kim ={name:'kim'};

const map = new Map([[lee,'developer'],[kim,'designer']]);

//Map rorcpsms Map.prototype의 Symbol.iterator 메소드를 상속받는 이터러블 이다.
console.log(Symbol.iterator in map) //true;

//이터러블인 Map객체는 for...of문으로 순회할 수 있다.
for(const entry of map)}{
console.log(entry) //[{name:'lee'}=>'developer'][{name:'kim'}=>'designer']
}

//이터러블인 Map객체는 스프레드 문법의 대상이 될수있다.
console.log([...map]);
//[[{name:'lee'},'developer'],[{name:'kim'},'designer']];

Map은 이터러블이면서 동시에 이터레이터인 객체를 반환하는 메소드를 제공한다.

  • Map.prototype.keys 메소드는 Map객체에서 요소 키를 값으로 갖는 이터레이터를 반환한다.
  • Map.prototype.values메소드는 Map객체에서 요소값을 값으로 갖는 이터레이터를 반환한다.
  • Map.prototype.entries메소드는 Map객체에서 요소 키와 요소 값을 값으로 갖는 이터레이터를 반환한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const lee = {name:'lee'};
const kim ={name:'kim'};

const map = new Map([lee,'developer'],[kim,'designer']);

for(const key of map.keys()){
consoel.log(key) //{name:'lee'}{name:'kim'}
}

for(const value of map.values()){
console.log(value) //developer designer
}
for(const entry of map.entries()){
console.log(entry) //[{name:'lee'},'developer'] [{name:'kim'},''designer];
}

Map객체는 요소의 순서에 의미를 갖지 않지만 Map객체를 순회하는 순서는 요소가 추가된 순서를 따른다.
이는 ECMAScript 사양에 규정되어 있지는 않지만 다른 이터러블의 순회와 호환성을 유지하기 위함이다.