Back to notes
mastery-frontend-typescript

จัดการข้อมูลด้วย Map และ Set ใน TypeScript

เมื่อ Array และ Object ธรรมดาไม่ตอบโจทย์ มารู้จักกับ Map และ Set ที่จัดการข้อมูลได้เร็วกว่าและยืดหยุ่นกว่า

January 29, 20262 min read readNNexis by Seereen

Overview

นอกจาก Array และ Object ทั่วไปแล้ว ES6 ได้นำเสนอ Data Structure ใหม่คือ Map และ Set ซึ่งใน TypeScript เราสามารถกำหนด Type ให้กับ Key และ Value ของมันได้อย่างชัดเจน ทำให้ปลอดภัยและทรงพลังมาก

Key Ideas

1. Map vs Object

  • Map: Key เป็น Type อะไรก็ได้ (Object, Function ก็ได้), มีลำดับการเก็บ, เช็คขนาดง่าย (.size), Performance ดีเมื่อมีการเพิ่มลบข้อมูลบ่อยๆ
  • Object: Key เป็นได้แค่ String/Symbol, ไม่มีลำดับที่แน่นอน, ต้องใช้ Object.keys().length เช็คขนาด

✅ Best Practice: ใช้ Map เมื่อต้องการ Dictionary ที่ Key ไม่ใช่ String หรือต้องการประสิทธิภาพสูง

2. Set

Collection ของข้อมูลที่ "ไม่ซ้ำกัน" (Unique) เหมาะสำหรับใช้กำจัดข้อมูลซ้ำออกจาก Array

Example

Using Map in TypeScript

HLJS TYPESCRIPT
// กำหนด Type: Key=number, Value=string
const userMap = new Map<number, string>();

userMap.set(1, "Alice");
userMap.set(2, "Bob");

console.log(userMap.get(1)); // "Alice"
console.log(userMap.has(3)); // false

// Iterate Map
for (const [id, name] of userMap) {
  console.log(`ID: ${id}, Name: ${name}`);
}

Using Set for Unique Values

HLJS TYPESCRIPT
const ids = [1, 2, 2, 3, 3, 4];
const uniqueIds = new Set(ids); // Set { 1, 2, 3, 4 }

// แปลงกลับเป็น Array
const cleanIds = Array.from(uniqueIds); // [1, 2, 3, 4]

// TypeScript Set<Type>
const tags = new Set<string>();
tags.add("js");
tags.add("ts");
tags.add("js"); // ไม่เพิ่มซ้ำ

Pitfalls (สิ่งที่ควรระวัง)

❌ 1. ใช้ Object Reference เป็น Key ใน Set/Map

ต้องระวังเรื่อง Reference Address เพราะ Object ที่หน้าตาเหมือนกันแต่คนละตัว จะถือว่าเป็นคนละ Key

HLJS TYPESCRIPT
const map = new Map();
map.set({ a: 1 }, "value");
console.log(map.get({ a: 1 })); // undefined (คนละ reference กัน)

References

Share this note

© 2026 My Notes by Seereen