เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลข สร้างอาร์เรย์ใหม่ที่แต่ละดัชนีเก็บผลรวมของสมาชิกตั้งแต่ต้นจนถึงดัชนีนั้น
ตัวอย่าง: [1,2,3,4,5] → [1, 3, 6, 10, 15]
ตัวอย่างโค้ด
const arr = [1, 2, 3, 4, 5];
const cumulativeSum = arr => {
let result = [arr[0]];
for (let i = 1; i < arr.length; i++) {
result.push(arr[i] + result[i-1]);
}
return result;
};
console.log(cumulativeSum(arr));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ 1, 3, 6, 10, 15 ]