Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เมธอด array.flatMap() ใน JavaScript: Map แล้ว Flatten ระดับเดียว

เมธอด flatMap() เป็นการรวม map() และ flat() (ระดับ 1) ในขั้นตอนเดียว ใช้สำหรับ แปลงแต่ละองค์ประกอบแล้วรวม (flatten) ผลลัพธ์เป็นอาร์เรย์ระดับเดียว

ไวยากรณ์ (Syntax)

array.flatMap(callback(currentValue[, index[, array]])[, thisArg])

เทียบเท่ากับ: arr.map(...).flat() หรือ arr.map(...).flat(1)

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1: แปลงตัวเลขและ flatten

<!DOCTYPE html>
<html>
<body>
  <h2>คะแนนอันดับ - flatMap</h2>
  <p>เพิ่ม 10 ให้แต่ละค่า แล้ว flatten</p>
  <button onclick="display()">ประมวลผล</button>
  <p id="demo"></p>
  <script>
    const pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000];
    
    // แสดง entries ก่อน
    const entries = pointsArr.flatMap(val => [val + 10]).entries();
    for (const val of entries) {
      document.getElementById("demo").innerHTML += val + "<br>";
    }
    
    function pointsFunc(points) {
      return points == 550;
    }
    
    function display() {
      document.getElementById("demo").innerHTML = 
        "มีค่า 550 หรือไม่? " + pointsArr.some(pointsFunc);
    }
  </script>
</body>
</html>

ตัวอย่างที่ 2: แปลงและขยายอาร์เรย์

<!DOCTYPE html>
<html>
<body>
  <h2>รหัสรถยนต์ - flatMap</h2>
  <button onclick="display()">ประมวลผล</button>
  <p id="demo"></p>
  <script>
    const carid = ["110", "230", "299", "399"];
    
    // แสดง entries ของ flatMap
    const entries = carid.flatMap(val => [val + 10]).entries();
    for (const val of entries) {
      document.getElementById("demo").innerHTML += val + "<br>";
    }
    
    function display() {
      document.getElementById("demo").innerHTML = 
        "อาร์เรย์หลัง slice(1,4) = " + carid.slice(1, 4);
    }
  </script>
</body>
</html>

ตัวอย่างที่ชัดเจนกว่า: ความแตกต่าง map vs flatMap

const arr = [1, 2, 3];

// map() - คืนอาร์เรย์ซ้อน
arr.map(x => [x, x * 10]); 
// [[1, 10], [2, 20], [3, 30]]

// flatMap() - flatten ระดับ 1 อัตโนมัติ
arr.flatMap(x => [x, x * 10]); 
// [1, 10, 2, 20, 3, 30]

// กรณี callback คืนค่าไม่ใช่อาร์เรย์ - flatMap จะ wrap ให้อัตโนมัติ
arr.flatMap(x => x * 10); 
// [10, 20, 30] (เหมือน map)

กรณีใช้งานจริง (Real-world Use Cases)

1. แยกคำในประโยค (Split sentences into words)

const sentences = [
  'Hello world',
  'JavaScript is awesome',
  'flatMap is useful'
];

// map + flat
const words1 = sentences.map(s => s.split(' ')).flat();
// ["Hello", "world", "JavaScript", "is", "awesome", "flatMap", "is", "useful"]

// flatMap - ทำในขั้นตอนเดียว
const words2 = sentences.flatMap(s => s.split(' '));
// ผลลัพธ์เหมือนกัน แต่มีประสิทธิภาพดีกว่าเล็กน้อย

2. กรองและแปลงพร้อมกัน (Filter + Map)

const numbers = [1, 2, 3, 4, 5, 6];

// ต้องการเฉพาะเลขคู่ และคูณ 2
const result = numbers.flatMap(n => 
  n % 2 === 0 ? [n * 2] : [] // คืนอาร์เรย์ว่างสำหรับเลขคี่ = กรองทิ้ง
);
// [4, 8, 12] (2*2, 4*2, 6*2)

3. จัดการข้อมูลซ้อน (Nested Data)

const departments = [
  {name: 'Engineering', employees: ['Alice', 'Bob']},
  {name: 'Marketing', employees: ['Carol']},
  {name: 'Sales', employees: ['Dave', 'Eve', 'Frank']}
];

// ดึงชื่อพนักงานทั้งหมด
const allEmployees = departments.flatMap(dept => dept.employees);
// ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank']

ข้อจำกัด

  • Flatten ได้แค่ระดับ 1 เท่านั้น (ไม่สามารถระบุ depth ได้เหมือน flat(depth))
  • หากต้องการ flatten หลายระดับ ให้ใช้ arr.map(...).flat(2) แทน