Set

Junyeong park·2022년 11월 13일

JavaScript

목록 보기
1/2
post-thumbnail

코딩테스트 문제를 풀던 도중 중복값만 제거하면 문제를 쉽게 접근할 것 같았다
어떻게 쉽고 빠르게 없앨까? 그 때 Set이 떠올랐다 이번에 확실하게 정리해야지..

Set이 뭔데? 언제? 왜? 쓰는거지?

💡Set 뭔데? ➡️ value(값)만 저장하며 중복을 허용하지 않는 collection

어떤 말일까? 코드를 보니 이해가 쉬웠다
콘솔로그를 통해 출력하니
'Hello!' 중 두 번 중복되는 값 인 'l'이 중복되는 수 만큼, 한 개 삭제 된 후,
Set(length값) { '갑', '값', ....}의 형태로 출력되는 것을 알 수 있었다
num같은 경우 숫자값이 때문에 ''없이 숫자의 값만 출력된다

let str = new Set ("Hello!");
console. log(str);
//output : Set(5) { 'H', 'e', 'l', 'o', '!' }
let num = new Set ([1, 2, 3, 4, 5]);
console.log(num);
//output : Set(5) { 1, 2, 3, 4, 5 }

요소의 추가 : Set.add(value), 요소의 존재 확인 : Set.has(value), 요소의 삭제 : Set.delete(value) 또한 해당 메소드를 통해 가능했다

  1. 요소의 추가 : Set.add(value)
let set = new Set();
set.add(1).add(2).add(4).add(6);
console.log(set);
//output : Set(4) { 1, 2, 4, 6 }
  1. 요소의 존재 확인 : Set.has(value)
let set = new Set();
set.add(1).add(2).add(4).add(6);
console.log(set.has(4));//output : true
console.log(set.has(10));//output : false
  1. 요소의 삭제 : Set.delete(value)
let set = new Set();
set.add(1).add(2).add(4).add(6);
set.delete(1);
console.log(set);//output : Set(3) { 2, 4, 6 }

💡Set 그래서 언제? 왜 써? ➡️ 배열의 중복 확인 용이 하다! ➡️ 중복제거하여 새로운 배열 생성하기 편하다

let arr = ['a', 'a', 'b', 'c']; // 기존 배열
let mySet = new Set(arr); // Set 생성
let arr2 = [...mySet]; 
// ['a', 'b', 'c'], 스프레드문법 활용하여 mySet의 값만 배열에 넣어준다

이처럼 Set통해 중복요소를 제거하기 용이하고, 제거한 값을 다시 새로운 배열로 만들어 활용하기 쉽다

☝🏼주의할 점 : Set은 인덱스 값으로 데이터를 조회하는 일을 할 수 없다.

const mySet = new Set("abcd");
const myArray = [..."abcd"];
myArray[0]; // "a"
mySet[0];   // undefined
profile
신입 개발자를 꿈꾸는 박준영입니다👨🏻‍💻

0개의 댓글