- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 ]
- Related Articles
- Tag names of body element's children in JavaScript?
- Make an array of another array's duplicate values in JavaScript
- How to change an element's class with JavaScript?
- Comparing adjacent element and swap - JavaScript?
- How to set the width of an element's border with JavaScript?
- How to set the style of an element's border with JavaScript?
- How to set an element's display type with JavaScript?
- JavaScript: Computing the average of an array after mapping each element to a value
- JavaScript's Boolean function?
- Which event occurs in JavaScript when an element's content is cut?
- Which event occurs in JavaScript when an element's content is pasted?
- Find average of each array within an array JavaScript
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- Calculating average of an array in JavaScript
- Average of array excluding min max JavaScript

Advertisements