Tổng quan
| Đặc điểm | Array | Set |
| Duplicate | Cho phép | Tự động loại bỏ |
| 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 |
| Kích thước | .length | .size |
| Iteration | for, forEach, map... | for...of, forEach |
| JSON.stringify | Hỗ trợ | Cần chuyển array [...set] |
Ví dụ so sánh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array vs 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; margin-right: 10px; }
</style>
</head>
<body>
<h1>Array vs Set</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button id="btnConvert">ARRAY → SET</button>
<button id="btnDisplay">HIỂN THỊ SET</button>
<h3>Nhấn nút để chuyển đổi và so sánh</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btnConvert = document.getElementById('btnConvert');
const btnDisplay = document.getElementById('btnDisplay');
const arr = [2, 3, 4, 2, 3, 4, 'A', 'A', 'B', 'B'];
let set1;
sampleEle.textContent = `Array: [${arr}] (length: ${arr.length})`;
btnConvert.addEventListener('click', () => {
set1 = new Set(arr);
resultEle.innerHTML = `Set: {${[...set1].join(', ')}} (size: ${set1.size})`;
});
btnDisplay.addEventListener('click', () => {
if (!set1) return alert('Chuyển đổi trước!');
resultEle.innerHTML = '';
set1.forEach((value, key, set) => {
resultEle.innerHTML += `Key: ${key}, Value: ${value}<br>`;
});
});
</script>
</body>
</html>
Kết quả
Array: [2, 3, 4, 2, 3, 4, A, A, B, B] (length: 10)
→ Set: {2, 3, 4, A, B} (size: 5)
Khi nào dùng Array, khi nào dùng Set?
✅ Dùng Array khi:
- Cần index truy cập ngẫu nhiên (arr[5])
- Cần duplicate values
- Cần order fixed, sort, reverse
- Cần JSON serialize trực tiếp
- Cần matrix/multi-dimensional
✅ Dùng Set khi:
- Cần unique values (tags, IDs, permissions)
- Cần check tồn tại nhanh (has O(1))
- Cần set operations: union, intersection, difference
- Duyệt theo insertion order
- Loại bỏ duplicate từ array
Chuyển đổi hai chiều
// Array → Set
const set = new Set(array);
const uniqueArray = [...new Set(array)];
// Set → Array
const array = [...set];
const array2 = Array.from(set);
// Array → Set → Array (unique)
const unique = arr => [...new Set(arr)];
WeakSet (Đặc biệt)
- Chỉ chứa object (không phải primitive)
- Weak reference - GC có thể dọn dẹp nếu không còn reference khác
- Không iterable, không có size, không clear
- Dùng để tag/mark object mà không ngăn GC
const ws = new WeakSet();
const obj = { id: 1 };
ws.add(obj);
ws.has(obj); // true
obj = null; // GC sẽ dọn obj và entry trong WeakSet