เมธอด Array.prototype.flat() ใช้สำหรับ "ทำให้แบน" (Flatten) อาร์เรย์ที่มีอาร์เรย์ซ้อนอยู่ภายใน โดยสร้างอาร์เรย์ใหม่ที่รวมค่าทั้งหมดอยู่ในระดับเดียว โดยไม่เปลี่ยนแปลงอาร์เรย์ต้นฉบับ
ไวยากรณ์
arr.flat([depth])
depth(ไม่บังคับ): ความลึกที่ต้องการทำให้แบน ค่าเริ่มต้นคือ1ใช้Infinityเพื่อทำให้แบนทุกระดับ
ตัวอย่าง: การใช้ flat() กับอาร์เรย์ซ้อนหลายระดับ
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array flat() Method</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 20px; font-weight: 500; }
button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
</style>
</head>
<body>
<h1>เมธอด Array.prototype.flat()</h1>
<div class="sample"><pre>[1, 2, 3, [4, 5], [6, [7, 8]]]</pre></div>
<div style="color: green;" class="result">หลัง flat(): <br></div>
<button class="Btn">คลิกเพื่อ Flat (depth 1)</button>
<h3>กดปุ่มด้านบนเพื่อทำให้อาร์เรย์ข้างต้นแบนที่ความลึก 1</h3>
<script>
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let arr = [1, 2, 3, [4, 5], [6, [7, 8]]];
document.querySelector(".Btn").addEventListener("click", () => {
// flat(1) - ทำให้แบนแค่ระดับ 1
let store = arr.flat(1);
store.forEach((item, index) => {
resEle.innerHTML += index + ' : ' + item + '<br>';
});
// แสดงผลลัพธ์ความลึกต่างๆ
resEle.innerHTML += '<br>flat() ค่าเริ่มต้น: ' + arr.flat();
resEle.innerHTML += '<br>flat(2): ' + arr.flat(2);
resEle.innerHTML += '<br>flat(Infinity): ' + arr.flat(Infinity);
});
</script>
</body>
</html>
ผลลัพธ์
อาร์เรย์ต้นฉบับ: [1, 2, 3, [4, 5], [6, [7, 8]]]
flat() / flat(1): [1, 2, 3, 4, 5, 6, [7, 8]]
flat(2): [1, 2, 3, 4, 5, 6, 7, 8]
flat(Infinity): [1, 2, 3, 4, 5, 6, 7, 8]
กรณีการใช้งานจริง
// รวมอาร์เรย์หลายชุด
let arrays = [[1, 2], [3, 4], [5, 6]];
let merged = arrays.flat(); // [1, 2, 3, 4, 5, 6]
// กรองค่า null/undefined พร้อมทำให้แบน
let data = [1, [2, null], [3, [4, undefined]]];
let clean = data.flat(Infinity).filter(x => x != null);
// [1, 2, 3, 4]
ข้อสังเกต
- ไม่เปลี่ยนแปลงอาร์เรย์ต้นฉบับ (Immutable)
- รองรับใน ES2019 (ES10) ขึ้นไป
- มีเมธอดคู่คือ
flatMap()ที่รวม map() และ flat() ไว้ด้วยกัน