Lab: Data Pipeline
Lab: Data Pipeline
Section titled “Lab: Data Pipeline”ใน lab นี้คุณจะใช้ array methods สร้าง data pipeline เพื่อวิเคราะห์ข้อมูลพนักงาน
ข้อมูลเริ่มต้น
Section titled “ข้อมูลเริ่มต้น”const employees = [ { id: 1, name: "สมชาย", dept: "engineering", salary: 55000, active: true }, { id: 2, name: "สมหญิง", dept: "design", salary: 48000, active: true }, { id: 3, name: "วิชัย", dept: "engineering", salary: 62000, active: false }, { id: 4, name: "นภา", dept: "engineering", salary: 71000, active: true }, { id: 5, name: "ประภา", dept: "design", salary: 52000, active: true }, { id: 6, name: "ธนา", dept: "marketing", salary: 45000, active: true }, { id: 7, name: "สุดา", dept: "marketing", salary: 47000, active: false },];-
กรองพนักงาน active
ใช้
filterเอาเฉพาะคนที่active === true -
หาเงินเดือนเฉลี่ยตามแผนก
จากพนักงาน active ใช้
reduceสร้าง object ที่มี key เป็นชื่อแผนก value เป็นเงินเดือนเฉลี่ย -
สร้าง summary report
ใช้ method chain สร้าง array ของ string:
"ชื่อ — แผนก — เงินเดือน"เรียงจากเงินเดือนมาก → น้อย (เฉพาะ active) -
ตรวจสอบเงื่อนไข
- ใช้
someเช็คว่ามีคนเงินเดือน > 70000 ไหม - ใช้
everyเช็คว่าทุกคนที่ active มีเงินเดือน > 40000 ไหม
- ใช้
Solution
Section titled “Solution”Show Solution
Step 1: กรอง active
const activeEmployees = employees.filter(e => e.active);// 5 คน (ไม่รวม วิชัย และ สุดา)Step 2: เงินเดือนเฉลี่ยตามแผนก
const avgByDept = activeEmployees.reduce((acc, e) => { if (!acc[e.dept]) { acc[e.dept] = { total: 0, count: 0 }; } acc[e.dept].total += e.salary; acc[e.dept].count += 1; return acc;}, {});
const avgSalaries = Object.fromEntries( Object.entries(avgByDept).map(([dept, data]) => [ dept, Math.round(data.total / data.count), ]));// { engineering: 63000, design: 50000, marketing: 45000 }Step 3: Summary report
const report = activeEmployees .sort((a, b) => b.salary - a.salary) .map(e => `${e.name} — ${e.dept} — ${e.salary.toLocaleString()} บาท`);
// ["นภา — engineering — 71,000 บาท",// "สมชาย — engineering — 55,000 บาท",// "ประภา — design — 52,000 บาท",// "สมหญิง — design — 48,000 บาท",// "ธนา — marketing — 45,000 บาท"]Step 4: ตรวจสอบเงื่อนไข
const hasHighEarner = activeEmployees.some(e => e.salary > 70000);// true (นภา 71000)
const allAbove40k = activeEmployees.every(e => e.salary > 40000);// true