JavaScript에서 배열(Array)을 Set(집합) 객체로 변환하는 것은 매우 간단합니다. new Set() 생성자에 배열을 인수로 전달하기만 하면 되며, 이 과정에서 중복된 값은 자동으로 제거됩니다.
Set이란 무엇인가?
Set은 ES6(ECMAScript 2015)에서 도입된 자료구조로, 중복 없는 고유한 값만 저장할 수 있습니다. 따라서 배열에서 중복 요소를 손쉽게 제거하고 싶을 때 Set으로 변환하는 방법이 널리 활용됩니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>Convert array to set</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">Convert</button>
<h3>Click on the above button to convert the above array into a set</h3>
<script>
let resultEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let arr = [2, 3, 4, 2, 3, 4, "A", "A", "B", "B"];
sampleEle.innerHTML = "arr = " + arr;
document.querySelector(".Btn").addEventListener("click", () => {
let set1 = new Set(arr);
resultEle.innerHTML = "set1 = " + [...set1] + "<br>";
});
</script>
</body>
</html>코드 설명
- 숫자와 문자열이 섞여 있고 중복 값이 포함된 배열
arr을 준비합니다. - 버튼을 클릭하면
new Set(arr)을 통해 배열 전체가 Set으로 변환됩니다. - 전개 연산자(
[...set1])를 사용해 Set을 다시 배열 형태로 출력하여 결과를 확인합니다.
출력 결과
페이지를 처음 열면 아래와 같이 원본 배열이 화면에 표시됩니다.

'Convert' 버튼을 클릭하면 다음과 같이 중복이 제거된 Set의 내용이 출력됩니다.

정리
배열을 Set으로 변환하려면 new Set(배열) 한 줄이면 충분합니다. 변환된 Set을 다시 배열로 되돌리고 싶다면 전개 연산자 [...set] 또는 Array.from(set)을 사용하면 됩니다. 이 기법은 배열에서 중복 값을 제거하는 가장 간결하고 효율적인 방법 중 하나입니다.