Array.flat() และ flatMap() — จัดการ nested arrays
flat() ยุบ nested array ให้แบน, flatMap() รวม map + flat ในขั้นตอนเดียว
// flat() — ยุบ 1 ชั้น by default
[1, [2, 3], [4, [5, 6]]].flat();
// [1, 2, 3, 4, [5, 6]]
// flat(Infinity) — ยุบทุกชั้น
[1, [2, [3, [4]]]].flat(Infinity);
// [1, 2, 3, 4]
// ลบ empty slots
[1, , 3].flat(); // [1, 3]
flatMap() — map แล้ว flat 1 ชั้น:
// แปลง sentences เป็น words
const sentences = ['hello world', 'foo bar'];
sentences.flatMap((s) => s.split(' '));
// ['hello', 'world', 'foo', 'bar']
// เทียบกับ map().flat() ที่ verbose กว่า
sentences.map((s) => s.split(' ')).flat();
// ผลเหมือนกัน แต่ flatMap() allocate น้อยกว่า 1 array กลาง
กรณีกรอง + transform พร้อมกัน:
const items = [{ tags: ['css', 'html'] }, { tags: ['js'] }, { tags: [] }];
// ดึง tags ทั้งหมดออกมาเป็น flat array
items.flatMap((item) => item.tags);
// ['css', 'html', 'js']
// return [] เพื่อ skip item — เหมือน filter แบบ inline
items.flatMap((item) => item.tags.length > 0 ? item.tags : []);
flatMap() ใช้บ่อยใน data transformation pipeline เพราะ concise กว่า reduce() และ readable กว่า map().flat()