สร้างอาร์เรย์ใหม่ที่แต่ละค่า = ค่าเฉลี่ยของเอลีเมนต์นั้นกับตัวก่อนหน้า (ตัวแรกคือตัวมันเอง)
ตัวอย่าง
[3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1] → [3, (3+5)/2=4, (5+7)/2=6, (7+8)/2=7.5, ...]
ตัวอย่างโค้ด
const consecutiveAverage = arr => arr.map((el, i, a) => (el + (a[i-1] || 0)) / (1 + !!i)); console.log(consecutiveAverage([3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1]));
ผลลัพธ์
[3, 4, 6, 7.5, 5.5, 4, 6, 5.5, 3, 5, 6, 3, 1.5]
คำอธิบาย Logic
a[i-1] || 0: ตัวก่อนหน้า (index 0 ใช้ 0)1 + !!i: หาร 1 สำหรับ index 0, หาร 2 สำหรับ index > 0!!iแปลง index เป็น boolean แล้วกลับเป็น 0/1
เวอร์ชันอ่านง่ายกว่า
const consecutiveAverage = arr => arr.map((el, i, a) => i === 0 ? el : (el + a[i-1]) / 2);