세트(Set)
- set 객체는 중복되지 않는 유일한 값들의 집합
- 요소 순서에 의미가 없음
- 인덱스로 요소에 접근할 수 없음
- 교집합, 합집합, 차집합, 여집합 등을 구현
세트(Set) 선언
const 세트명 = new Set([요소1, 요소2, 요소3, ..]);
const set = new Set([1,2,3,4,5]);
console.log(set); // Set(5) {1, 2, 3, 4, 5}
size
- set의 길이를 반환
const set = new Set([1,2,3,4,5]);
console.log(set.size); // 5
has()
- set의 값의 유무를 boolean으로 반환
const set = new Set([1,2,3,4,5]);
console.log(set.has(2)); // true
console.log(set.has(10)); // false
반복문 사용
const set = new Set([1,2,3,4,5]);
// forEach()
set.forEach((item) => console.log(item));
// for of set
for(let value of set){
console.log(value);
}
// for of set.values()
for(let value of set.values()){
console.log(value);
}
add()
- set에 값을 추가
const set = new Set([1,2,3,4,5]);
set.add(6);
console.log(set); // Set(6) {1, 2, 3, 4, 5, 6}
// 중복을 포함하지 않으므로 추가가 안됨
set.add(6);
console.log(set); // Set(6) {1, 2, 3, 4, 5, 6}
delete()
- set에 특정 값 삭제
const set = new Set([1,2,3,4,5]);
set.delete(6);
console.log(set); // Set(5) {1, 2, 3, 4, 5}
clear()
- set 값 전부 삭제
const set = new Set([1,2,3,4,5]);
set.clear();
console.log(set); // Set(0) {size: 0}
object 객체 활용
const obj1= {name:'사과', emoji:'🍎', price:1000};
const obj2= {name:'바나나', emoji:'🍌', price:2000};
// object 객체를 set에 담기
const set2 = new Set([obj1, obj2]);
console.log(set2); // Set(2) {{…}, {…}}
obj1.price = 1500; // 프로퍼티 값을 변경하더라도 객체를 참조하는 주소는 변하지 않음
set2.add(obj1); // 중복값을 포함하지 않으므로 추가되지 않음
console.log(set2); // Set(2) {{…}, {…}}
const obj3 = {name:'사과', emoji:'🍎', price:1000};
set2.add(obj3); // obj3과 obj1은 프로퍼티와 값은 똑같지만 서로 다른 주소를 참조하고 있는 객체이므로 추가됨
console.log(set2); // Set(3) {{…}, {…}, {…}}
문제1
- 주어진 배열에서 중복을 제거해보자!
- (단, set을 이용하여 중복제거)
const fruits = ['🍎', '🍊', '🍎', '🍉', '🍌', '🍓', '🍌', '🍋', '🍈'];
// 직접 푼 코드
const set = new Set([]);
for(i in fruits){
set.add(fruits[i]);
}
console.log(set); // Set(7) {'🍎', '🍊', '🍉', '🍌', '🍓', …}
// 강사님 코드
function removeDuplaction(arr) {
return [...new Set(arr)]
}
console.log(removeDuplaction(fruits)); // Set(7) {'🍎', '🍊', '🍉', '🍌', '🍓', …}
문제2
- 주어진 두 세트의 공통된 아이템만 담고 있는 세트를 생성해보자
const set1 = new Set([1,2,3,4,5]);
const set2 = new Set([1,2,3,4]);
// 직접 푼 코드
const set3 = new Set([]);
set1.forEach((item) => {if (set2.has(item)) set3.add(item) });
console.log(set3); // Set(3) {1, 2, 3}
// 강사님 코드
function findInterSection(set1, set2) {
return new Set([...set1].filter((item) => set2.has(item)))
}
console.log(findInterSection(set1,set2)); // Set(3) {1, 2, 3}
'JavaScript' 카테고리의 다른 글
37. 예외처리 (0) | 2023.04.13 |
---|---|
36. 맵(map) (0) | 2023.04.13 |
34. 스프레드(Spread) (0) | 2023.04.12 |
33. 제너레이터(Generator) (0) | 2023.04.12 |
32. 이터레이터(Iterator) (0) | 2023.04.12 |