ฟังก์ชันนี้รับอาร์เรย์และตัวเลข n แล้วคืนออบเจ็กต์ที่นับจำนวนสมาชิกที่มากกว่าและน้อยกว่า n (ไม่นับค่าที่เท่ากับ n)
ตัวอย่าง
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const n = 3;
// ผลลัพธ์: { greater: 8, smaller: 1 }
ตัวอย่างโค้ด
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const greaterSmallerNumbers = (arr, num) => {
return arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if (val > num) {
greater++;
}
if (val < num) {
smaller++;
}
return { greater, smaller };
}, {
greater: 0,
smaller: 0
});
};
console.log(greaterSmallerNumbers(arr, 3));
การทำงาน
- ใช้
reduce()สะสมค่าในออบเจ็กต์ accumulator - เปรียบเทียบแต่ละสมาชิกกับ
num - เพิ่มตัวนับ
greaterหรือsmallerตามเงื่อนไข - คืนออบเจ็กต์สรุปผล
ผลลัพธ์
{ greater: 8, smaller: 1 }
ประยุกต์ใช้: การวิเคราะห์ข้อมูลสถิติ การกรองข้อมูล หรือการตัดสินใจแบบมีเงื่อนไข