Learn
← Previous Next →

Hari 11: Map, Set & Symbol

55 min Last updated 09 Apr 2026

Map — Key-Value dengan Tipe Apapun

const map = new Map();

// Set — bisa key apapun (objek, fungsi, dll)
map.set("nama", "Budi");
map.set(42, "angka sebagai key");
map.set(true, "boolean sebagai key");

map.get("nama");    // "Budi"
map.has(42);        // true
map.size;           // 3
map.delete(true);

// Iterasi
for (const [key, val] of map) {
    console.log(`${key}: ${val}`);
}

// Dari array of pairs
const mapDariArr = new Map([["a", 1], ["b", 2], ["c", 3]]);

Set — Kumpulan Nilai Unik

const set = new Set([1, 2, 3, 2, 1, 4, 3]);
console.log([...set]); // [1, 2, 3, 4] — duplikat dihapus

set.add(5);
set.has(3);     // true
set.delete(2);
set.size;       // 4

// Hapus duplikat dari array
const arr = [1, 2, 2, 3, 3, 4];
const unik = [...new Set(arr)]; // [1, 2, 3, 4]

// Interseksi dua Set
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
const intersection = new Set([...a].filter(x => b.has(x))); // {3, 4}

💡 Notice: Set secara otomatis menghapus duplikat. .size adalah properti (bukan method) untuk jumlah elemen.

Assignment

Dari array kata = ["apel", "mangga", "pisang", "apel", "jeruk", "mangga", "durian"]. Gunakan Set untuk (1) dapatkan kata unik, (2) hitung berapa duplikat yang dihapus, (3) tampilkan kata unik diurutkan alfabet.

Expected output:

Kata unik: apel, durian, jeruk, mangga, pisang
Duplikat dihapus: 2
JS script.js
Solution
Output