 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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));  Output
This will produce the following output in console −
[ 3, 4, 6, 7.5, 5.5, 4, 6, 5.5, 3, 5, 6, 3, 1.5 ]
Advertisements
 