Array.reduceRight()
เหมือน reduce() แต่ประมวลผลจาก ขวาไปซ้าย (Right-to-Left) รวมสมาชิกทั้งหมดเป็นค่าเดียว
ไวยากรณ์
arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
ตัวอย่าง: รวม Nested Arrays จากขวาไปซ้าย
<html> <body> <script>
const arr = [ [1, 2, 3], ['x', 'y', 'z'], [9, 10] ];
const result = arr.reduceRight((prev, curr) => prev.concat(curr));
document.write(result); // 9,10,x,y,z,1,2,3
</script> </body> </html>
ผลลัพธ์
9,10,x,y,z,1,2,3
คำอธิบาย
-
เริ่มจาก Index สุดท้าย:
- ต่อด้วย Index 1:
['x', 'y', 'z']→[9, 10, 'x', 'y', 'z'] - ต่อด้วย Index 0:
[1, 2, 3]→[9, 10, 'x', 'y', 'z', 1, 2, 3]
[9, 10] (Accumulator เริ่มต้น)
เมื่อไหร่ควรใช้ reduceRight()?
- ต้องการประมวลผลตามลำดับย้อนกลับ
- Composition ของ Functions (Right-to-Left)
- แปลง Nested Array เป็น Flat Array โดยรักษาลำดับกลุ่มจากท้าย