Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển đổi Array sang Set trong JavaScript

Cách đơn giản nhất

const uniqueArray = [...new Set(originalArray)];

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</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}]`;

        btn.addEventListener('click', () => {
            const set1 = new Set(arr);
            resultEle.innerHTML = `Set: {${[...set1].join(', ')}}<br>`;
            resultEle.innerHTML += `Mảng unique: [${[...set1]}]`;
        });
    </script>
</body>
</html>

Kết quả

Mảng gốc: [2, 3, 4, 2, 3, 4, A, A, B, B]
Set: {2, 3, 4, A, B}
Mảng unique: [2, 3, 4, A, B]

Các trường hợp đặc biệt

1. NaN trong Set

const arr = [NaN, NaN, 1, 2];
const set = new Set(arr); // {NaN, 1, 2} - NaN === NaN trong Set!

2. Object/Array trong Set (tham chiếu)

const arr = [{a:1}, {a:1}, {a:2}];
const set = new Set(arr); // 3 phần tử - object khác reference
// Muốn unique by value: cần serialize hoặc custom logic

3. Unique by property

const users = [
    {id: 1, name: 'A'},
    {id: 2, name: 'B'},
    {id: 1, name: 'A'} // duplicate id
];

// Cách 1: Map (giữ object cuối)
const uniqueById = [...new Map(users.map(u => [u.id, u])).values()];

// Cách 2: Filter + Set seen
const seen = new Set();
const unique = users.filter(u => {
    if (seen.has(u.id)) return false;
    seen.add(u.id);
    return true;
});

Performance

// 100,000 phần tử
Array.includes(): ~O(n) each → O(n²) total
Set.has(): ~O(1) each → O(n) total

// Benchmark: unique 100k items
// Array.filter + indexOf: ~2000ms
// Set: ~5ms

Polyfill cho IE (nếu cần)

// Array.from + Set polyfill
if (!Array.from) {
    Array.from = (iterable) => [...iterable];
}
// Hoặc dùng core-js