Thrice sum of elements of array - JavaScript

We are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as sum of three consecutive elements from the original array.

For example, if the input array is:

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Then the output should be:

const output = [3, 12, 21, 9];

The function groups elements in sets of three and calculates their sum: (0+1+2=3), (3+4+5=12), (6+7+8=21), and (9+0+0=9) for the remaining element.

How It Works

The algorithm iterates through the array with a step of 3, taking three elements at a time. If fewer than three elements remain, it treats missing elements as 0.

Original Array: 0 1 2 3 4 5 6 7 8 9 Grouped Sums: 3 12 21 9 0+1+2 = 3 3+4+5 = 12 6+7+8 = 21 9+0+0 = 9

Example

Following is the code:

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const thriceSum = arr => {
    if (!arr.length) {
        return [];
    }
    
    const res = [];
    for (let i = 0; i < arr.length; i += 3) {
        res.push(arr[i] + (arr[i+1] || 0) + (arr[i+2] || 0));
    }
    
    return res;
};

console.log(thriceSum(arr));

Output

This will produce the following output in console:

[ 3, 12, 21, 9 ]

Step-by-Step Breakdown

Let's trace through the execution:

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log("Step 1 (i=0):", arr[0] + (arr[1] || 0) + (arr[2] || 0)); // 0+1+2 = 3
console.log("Step 2 (i=3):", arr[3] + (arr[4] || 0) + (arr[5] || 0)); // 3+4+5 = 12
console.log("Step 3 (i=6):", arr[6] + (arr[7] || 0) + (arr[8] || 0)); // 6+7+8 = 21
console.log("Step 4 (i=9):", arr[9] + (arr[10] || 0) + (arr[11] || 0)); // 9+0+0 = 9
Step 1 (i=0): 3
Step 2 (i=3): 12
Step 3 (i=6): 21
Step 4 (i=9): 9

Key Points

  • The || 0 operator handles cases where array elements don't exist
  • The loop increments by 3 (i += 3) to process groups of three
  • Empty arrays return an empty result array
  • Remaining elements (less than 3) are padded with zeros

Conclusion

This function efficiently groups array elements in threes and calculates their sum. The use of logical OR (|| 0) elegantly handles arrays whose length isn't divisible by three.

Updated on: 2026-03-15T23:18:59+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements