Array of adjacent element's average - JavaScript

Let's say, we have an array of numbers:

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

We are required to write a function that returns an array with the average of the corresponding element and its predecessor. For the first element, as there are no predecessors, so that very element should be returned.

Let's write the code for this function, we will use the Array.prototype.map() function to solve this problem:

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
]

How It Works

The function uses Array.map() to transform each element. For each position:

  • first: Gets the previous element or 0 if none exists
  • second: Uses 1 + !!ind to get 1 for index 0 (first element) or 2 for other indices
  • return: Calculates (current + previous) / divisor

Alternative Approach

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

const consecutiveAverage = arr => {
    return arr.map((el, ind) => {
        if (ind === 0) {
            return el; // First element stays the same
        }
        return (el + arr[ind - 1]) / 2; // Average of current and previous
    });
};

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

Conclusion

Both approaches calculate adjacent averages using Array.map(). The second version is more readable, explicitly handling the first element case and averaging subsequent elements with their predecessors.

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

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements