Cumulative average of pair of elements in JavaScript

We have an array of numbers and need to write a function that returns an array with the average of each element and its predecessor. For the first element, since there's no predecessor, we return the element itself.

Let's implement this using the Array.prototype.map() method to transform each element based on its position.

How It Works

The algorithm works as follows:

  • For the first element (index 0): return the element itself
  • For other elements: calculate (current + previous) / 2

Example

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

const consecutiveAverage = arr => {
    return arr.map((el, ind, array) => {
        const first = (array[ind-1] || 0);
        const second = (1 + !!ind);
        return ((el + first) / second);
    });
};

console.log(consecutiveAverage(arr));
[
  3, 4, 6, 7.5, 5.5, 4,
  6, 5.5, 3, 5, 6, 3,
  1.5
]

Step-by-Step Breakdown

Let's understand the calculation for the first few elements:

const arr = [3, 5, 7, 8];

// Element at index 0: 3
// No predecessor, so return 3

// Element at index 1: 5
// Average of 5 and 3 = (5 + 3) / 2 = 4

// Element at index 2: 7
// Average of 7 and 5 = (7 + 5) / 2 = 6

// Element at index 3: 8
// Average of 8 and 7 = (8 + 7) / 2 = 7.5

console.log("First element:", 3);
console.log("Second element:", (5 + 3) / 2);
console.log("Third element:", (7 + 5) / 2);
console.log("Fourth element:", (8 + 7) / 2);
First element: 3
Second element: 4
Third element: 6
Fourth element: 7.5

Alternative Implementation

Here's a more readable version of the same function:

const consecutiveAverageSimple = arr => {
    return arr.map((current, index) => {
        if (index === 0) {
            return current;  // First element has no predecessor
        }
        const previous = arr[index - 1];
        return (current + previous) / 2;
    });
};

const numbers = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];
console.log(consecutiveAverageSimple(numbers));
[
  3, 4, 6, 7.5, 5.5, 4,
  6, 5.5, 3, 5, 6, 3,
  1.5
]

Conclusion

The cumulative average function transforms an array by calculating the average of each element with its predecessor. The map() method provides an elegant solution for this array transformation problem.

Updated on: 2026-03-15T23:19:00+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements