[JavaScript]-Set 객체

2023. 5. 5. 00:57프론트엔드 과거의 흔적

1. Set 객체와 배열

 

Set 객체는 중복되지 않는 유일한 값들의 집합입니다. Set 객체는 배열과 유사한 점이 많지만 다음과 같은 차이가 있습니다.

 

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

또한 Set 객체는 수학적 집합을 구현하기 위한 자료구조이기에 Set를 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있습니다.

Set 객체는 Set 생성자 함수로 생성하며 이 때 인수를 전달하지 않으면 빈 Set 객체가 생성됩니다.

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

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

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 객체의 특성을 활용하여 배열에서 중복된 요소를 제거할 수 있습니다.

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]

// 배열의 중복된 요소 제거

const uniq = array => [...new Set(array)];
console.log(uniq([2, 1, 2, 3, 4, 3, 4])); // [2, 1, 3, 4]

// Set을 사용한 배열의 중복 요소 제거

2. Set 객체의 요소 개수 확인

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

const { size } = new Set([1, 2, 3, 3]);
console.log(size); // 3

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

 

3. Set 객체를 활요한 집합 연산

* 교집합

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}

* 합집합

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}