เมธอด Array.prototype.flat() ใช้สำหรับ "แบน" (flatten) อาร์เรย์ซ้อนหลายชั้นให้กลายเป็นอาร์เรย์ชั้นเดียว โดยสามารถระบุความลึก (depth) ได้ ค่าเริ่มต้นคือ 1
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>แบนอาร์เรย์หลายมิติ</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 20px; font-weight: 500; }
.sample { color: #666; }
</style>
</head>
<body>
<h1>การแบนอาร์เรย์หลายมิติใน JavaScript</h1>
<div class="sample"><pre>[1, 2, 3, [4, 5], [6, [7, 8]]]</pre></div>
<div style="color: green;" class="result">หลังแบน (depth 2): <br /></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อแบนอาร์เรย์ด้วยความลึก 2</h3>
<script>
const resEle = document.querySelector(".result");
const sampleEle = document.querySelector(".sample");
const arr = [1, 2, 3, [4, 5], [6, [7, 8]]];
document.querySelector(".Btn").addEventListener("click", () => {
const flattened = arr.flat(2);
flattened.forEach((item, index) => {
resEle.innerHTML += index + " : " + item + "<br>";
});
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

รายละเอียดเพิ่มเติม
arr.flat()— แบน 1 ระดับ (default)arr.flat(2)— แบน 2 ระดับarr.flat(Infinity)— แบนทุกระดับจนหมด- เมธอดนี้คืนอาร์เรย์ใหม่ ไม่แก้ไขอาร์เรย์เดิม
- รองรับใน ES2019 (ES10) ขึ้นไป
ทางเลือกเก่า (Polyfill)
// ก่อนมี flat() ใช้ reduce + concat
const flatten = (arr, depth = 1) =>
depth === 0 ? arr :
arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val, depth - 1) : val), []);