Khái niệm
Set (ES2015) là tập hợp các giá trị duy nhất (unique). Chuyển Array → Set tự động loại bỏ duplicate. Set không có index, duyệt theo thứ tự insertion.
Cú pháp
const set = new Set(array);
const uniqueArray = [...new Set(array)]; // Quay lại array
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array to Set</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 15px; border-radius: 4px; }
.sample { color: #6a1b9a; background: #f3e5f5; }
.result { color: #d32f2f; background: #ffebee; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Chuyển Array sang Set (Loại bỏ duplicate)</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button id="btn">CHUYỂN ĐỔI</button>
<h3>Nhấn nút để chuyển mảng trên thành Set</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
const arr = [2, 3, 4, 2, 3, 4, 'A', 'A', 'B', 'B'];
sampleEle.textContent = `Mảng gốc: [${arr}] (${arr.length} phần tử)`;
btn.addEventListener('click', () => {
const set1 = new Set(arr);
const uniqueArr = [...set1];
resultEle.innerHTML = `Set: {${[...set1].join(', ')}} (${set1.size} phần tử unique)<br>`;
resultEle.innerHTML += `Mảng unique: [${uniqueArr}]`;
});
</script>
</body>
</html>
Kết quả
Mảng gốc: [2, 3, 4, 2, 3, 4, A, A, B, B] (10 phần tử)
Set: {2, 3, 4, A, B} (5 phần tử unique)
Mảng unique: [2, 3, 4, A, B]
Các thao tác phổ biến với Set
1. Thêm/Xóa/Kiểm tra
const set = new Set([1, 2, 3]);
set.add(4); // Thêm
set.delete(2); // Xóa
set.has(3); // true
set.clear(); // Xóa tất cả
set.size; // Số lượng
2. Duyệt Set
for (const item of set) { ... }
set.forEach((value, valueAgain, set) => { ... });
[...set] // Spread to array
3. Set Operations (Toán học)
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
// Union (Hợp)
const union = new Set([...a, ...b]); // {1,2,3,4,5}
// Intersection (Giao)
const intersection = new Set([...a].filter(x => b.has(x))); // {3}
// Difference (Hiệu a - b)
const diff = new Set([...a].filter(x => !b.has(x))); // {1,2}
// Symmetric Difference (XOR)
const xor = new Set([...a].filter(x => !b.has(x)).concat([...b].filter(x => !a.has(x)))); // {1,2,4,5}
4. Ứng dụng thực tế
// Loại bỏ duplicate từ API response
const uniqueUsers = [...new Set(users.map(u => u.email))].map(email =>
users.find(u => u.email === email)
);
// Count unique values
const colorCounts = [...new Set(colors)].map(c => ({
color: c,
count: colors.filter(x => x === c).length
}));
// Tag system
const allTags = [...new Set(posts.flatMap(p => p.tags))];
Set vs Array
| Đặc điểm | Array | Set |
|---|---|---|
| Duplicate | Cho phép | Không cho phép |
| Truy cập | Index (arr[0]) | Không có index |
| Kiểm tra tồn tại | O(n) - includes | O(1) - has() |
| Thứ tự | Index order | Insertion order |
| Key/Value | Index/Value | Value/Value (key = value) |