그럼에도 불구하고

👨‍💻

[Javascript] Set이란? 본문

JavaScript/JavaScript basics

[Javascript] Set이란?

zenghyun 2023. 1. 25. 18:35

 

Set에 대해 알아보자

 

[ 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]

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

 

 

[ Set.prototype.size ]

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

 

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

 

 

[ Set.prototype.add ]

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

 

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

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

 

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

 

const set = new Set();

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

 

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

 

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, {}, []}

 

[ Set.prototype.has ]

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

has 메서드는 특정 요소의 존재 여부를 나타내는 불리언 값을 반환한다.

 

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

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

 

[ Set.prototype.delete ]

Set 객체의 특정 요소를 삭제하려면 Set.prototype.delete 메서드를 사용한다.

delete 메서드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다. delete 메서드는 인덱스가 아니라 삭제하려는 요소값을 인수로 전달해야 한다. Set 객체는 순서에 의미가 없다. 

 

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 객체의 요소를 삭제하려 하면 에러 없이 무시된다.

 

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

// 존재하지 않는 요소 0을 삭제하면 에러없이 무시된다.
set.delete(0);
console.log(set); // Set(3) {1, 2, 3}

 

[ Set.prototype.clear ]

Set 객체의 모든 요소를 일괄 삭제하려면 Set.prototype.clear 메서드를 사용한다. clear 메서드는 언제나 undefined를 반환한다. 

 

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

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

 

[ Set을 이용한 집합 연산 ]

 

교집합 

// 교집합
//  ver 1 
Set.prototype.intersection = function (set) {
  const result = new Set();

  for (const value of set) {
    if (this.has(value)) result.add(value);
  }
  return result;
};

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

console.log(setA.intersection(setB)); // Set(3) {1, 3, 8}
console.log(setB.intersection(setA)); // Set(3) {1, 3, 8}

// ver2 
Set.prototype.intersection2 = function (set) {
  return new Set([...this].filter(v => set.has(v)));
};

console.log(setA.intersection2(setB)); // Set(3) {1, 3, 8}
console.log(setB.intersection2(setA)); // Set(3) {1, 3, 8}

 

 

합집합 

//합집합
// ver 1 
Set.prototype.union = function (set) {
  const result = new Set(this);

  for (const value of set) {
    result.add(value);
  }
  return result;
};

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

console.log(setA.union(setB)); // Set(5) { 1, 2, 3, 6, 8 }
console.log(setB.union(setA)); // Set(5) { 1, 3, 8, 2, 6 }

// ver2 
Set.prototype.union2 = function (set) {
  return new Set([...this, ...set]);
}

console.log(setA.union2(setB)); // Set(5) { 1, 2, 3, 6, 8 }
console.log(setB.union2(setA)); // Set(5) { 1, 3, 8, 2, 6 }

 

 

차집합

//차집합
// ver 1 
Set.prototype.difference = function (set) {
  const result = new Set(this);

  for (const value of set) {
    result.delete(value);
  }
  return result;
};

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

console.log(setA.difference(setB)); // Set(2) { 2, 6 }
console.log(setB.difference(setA)); // Set(0) { }

// ver 2 
Set.prototype.difference2 = function (set) {
  return new Set([...this].filter(v => !set.has(v)));
};

console.log(setA.difference2(setB)); // Set(2) { 2, 6 }
console.log(setB.difference2(setA)); // Set(0) { }

 

부분 집합

// 부분 집합
// ver1
Set.prototype.isSuperset = function (set) {
  for (const value of set) {
    if (!this.has(value)) return false;
  }
  return true;
}

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

console.log(setA.isSuperset(setB)); // true
console.log(setB.isSuperset(setA)); // false

// ver2 
Set.prototype.isSuperset2 = function (subset) {
  const superseArr = [...this];
  return [...subset].every(v => superseArr.includes(v));
};


console.log(setA.isSuperset2(setB)); // true
console.log(setB.isSuperset2(setA)); // false

 

 

Comments