หัวข้อ 5: Array Methods map, filter, reduce, find, forEach

คำจำกัดความ

Array Methods คือฟังก์ชันสำเร็จรูปของ array ที่ช่วยวนซ้ำ แปลง กรอง ค้นหา หรือสรุปข้อมูล โดยทำให้โค้ดอ่านง่ายกว่า loop ในหลายกรณี

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
  A["Array
ข้อมูลตั้งต้น"] --> B["filter()
กรองข้อมูล"] B --> C["map()
แปลงข้อมูล"] C --> D["reduce()
สรุปเป็นค่าเดียว"] A --> E["find()
หา element แรก"] A --> F["forEach()
วนทำงาน"]

ตารางเปรียบเทียบ

Method คืนค่าใหม่ ใช้สำหรับ
forEach ไม่คืน array ใหม่ วนทำ side effect
map array ใหม่ขนาดเท่าเดิม แปลงข้อมูล
filter array ใหม่ขนาดอาจลดลง กรองข้อมูล
reduce ค่าเดียว รวม/สรุปข้อมูล
find element หรือ undefined หาตัวแรกที่ตรงเงื่อนไข

forEach

const lessons = ["HTML", "CSS", "JavaScript"];

lessons.forEach((lesson, index) => {
  // แสดงลำดับและชื่อบทเรียน
  console.log(`${index + 1}. ${lesson}`);
});

map

const scores = [60, 75, 90];

const scoreLabels = scores.map(score => {
  // แปลงคะแนนเป็นข้อความ
  return `คะแนน ${score}`;
});

console.log(scoreLabels); // ["คะแนน 60", "คะแนน 75", "คะแนน 90"]

filter

const students = [
  { name: "Ana", score: 82 },
  { name: "Ben", score: 45 },
  { name: "Cam", score: 68 }
];

const passed = students.filter(student => {
  // เก็บเฉพาะผู้ที่คะแนนตั้งแต่ 50
  return student.score >= 50;
});

console.log(passed);

reduce

const scores = [60, 75, 90];

const total = scores.reduce((acc, cur) => {
  // acc คือผลรวมสะสม, cur คือค่าปัจจุบัน
  return acc + cur;
}, 0);

console.log(total); // 225

find

const users = [
  { id: 1, name: "Ana" },
  { id: 2, name: "Ben" }
];

const user = users.find(item => item.id === 2);
console.log(user); // { id: 2, name: "Ben" }

Methods อื่นที่ควรรู้

Method Chaining

const students = [
  { name: "Ana", score: 82 },
  { name: "Ben", score: 45 },
  { name: "Cam", score: 68 }
];

const averagePassedScore = students
  .filter(student => student.score >= 50) // กรองผู้ผ่าน
  .map(student => student.score) // แปลงเป็น array คะแนน
  .reduce((sum, score, index, arr) => {
    // ถ้าเป็นตัวสุดท้ายให้คืนค่าเฉลี่ย
    const total = sum + score;
    return index === arr.length - 1 ? total / arr.length : total;
  }, 0);

console.log(averagePassedScore); // 75

สมการ Reduce เพื่อหาผลรวม

sum = i=0 n-1 ai

โดยที่ sum คือผลรวมทั้งหมด, n คือจำนวนสมาชิกใน array, และ aᵢ คือค่าสมาชิก array ที่ index i

แบบทดสอบหลังเรียน

  1. forEach ต่างจาก map อย่างไร
  2. filter คืนค่าอะไร
  3. reduce เหมาะกับงานแบบใด
  4. find และ filter ต่างกันอย่างไร
  5. Method chaining มีข้อดีและข้อควรระวังอะไร

กลับสัปดาห์ที่ 4