Docs/JavaScript/Map & Set

Map & Set

Map

Seperti Object tapi key bisa tipe apapun.

  • .set(key, value)
  • .get(key)
  • .has(key)
  • .delete(key)
  • .size

Set

Koleksi nilai unik (tidak ada duplikat).

  • .add(value)
  • .has(value)
  • .delete(value)
  • .size
script.js
Try It →
// Map
const scores = new Map();
scores.set("Ali", 95);
scores.set("Budi", 87);
scores.set("Cici", 92);

// Set
const unique = new Set([1,2,2,3,3,3,4,5,5]);
const tags = new Set(["html","css","js","html","css"]);

const o = document.getElementById('output');
o.innerHTML = 
  '// Map
'+
  'scores.get("Ali") → '+scores.get("Ali")+'
'+
  'scores.has("Budi") → '+scores.has("Budi")+'
'+
  'scores.size → '+scores.size+'

'+
  '// Set (auto-removes duplicates!)
'+
  'new Set([1,2,2,3,3,3,4,5,5])
→ '+JSON.stringify([...unique])+'

'+
  'new Set(["html","css","js","html","css"])
→ '+JSON.stringify([...tags])+'

'+
  '// Array dedup trick:
'+
  '[...new Set(array)]';