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 |
หาตัวแรกที่ตรงเงื่อนไข |
forEachconst lessons = ["HTML", "CSS", "JavaScript"];
lessons.forEach((lesson, index) => {
// แสดงลำดับและชื่อบทเรียน
console.log(`${index + 1}. ${lesson}`);
});
mapconst scores = [60, 75, 90];
const scoreLabels = scores.map(score => {
// แปลงคะแนนเป็นข้อความ
return `คะแนน ${score}`;
});
console.log(scoreLabels); // ["คะแนน 60", "คะแนน 75", "คะแนน 90"]
filterconst 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);
reduceconst scores = [60, 75, 90];
const total = scores.reduce((acc, cur) => {
// acc คือผลรวมสะสม, cur คือค่าปัจจุบัน
return acc + cur;
}, 0);
console.log(total); // 225
findconst users = [
{ id: 1, name: "Ana" },
{ id: 2, name: "Ben" }
];
const user = users.find(item => item.id === 2);
console.log(user); // { id: 2, name: "Ben" }
findIndex(): คืน index ของ element แรกที่ตรงเงื่อนไขsome(): มีอย่างน้อยหนึ่งรายการตรงเงื่อนไขหรือไม่every(): ทุกตัวตรงเงื่อนไขหรือไม่includes(): มีค่านี้อยู่หรือไม่flat(): flatten array ซ้อนflatMap(): map แล้ว flatten หนึ่งระดับ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
โดยที่ sum คือผลรวมทั้งหมด, n คือจำนวนสมาชิกใน array, และ aᵢ คือค่าสมาชิก array ที่ index i
forEach ต่างจาก map อย่างไรfilter คืนค่าอะไรreduce เหมาะกับงานแบบใดfind และ filter ต่างกันอย่างไร