# Find consecutive elements average JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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 consecutiveAverage = arr => {
return arr.map((el, ind, array) => {
return ((el + (array[ind-1] || 0)) / (1 + !!ind));
});
};
console.log(consecutiveAverage(arr));

## Output

The output in the console will be −

[
3, 4, 6, 7.5, 5.5, 4,
6, 5.5, 3, 5, 6, 3,
1.5
]
Updated on 26-Aug-2020 11:21:55