w3resource

JavaScript: Compute the average of an array, after mapping each element to a value using the provided function

JavaScript fundamental (ES6 Syntax): Exercise-57 with Solution

Write a JavaScript program to compute the average of an array, after mapping each element to a value using the provided function.

  • Use Array.prototype.map() to map each element to the value returned by fn.
  • Use Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0.
  • Divide the resulting array by its length.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const averageBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
  arr.length;

console.log(averageBy([{ a: 40 }, { a: 20 }, { a: 80 }, { a: 60 }], o => o.a));
console.log(averageBy([{ a: 4 }, { a: 2 }, { a: 8 }, { a: 6 }], 'a'));

Sample Output:

50
5

Pictorial Presentation:

JavaScript Fundamental: Compute the average of an array, after mapping each element to a value using the provided function

Flowchart:

flowchart: Compute the average of an array, after mapping each element to a value using the provided function

Live Demo:

See the Pen javascript-basic-exercise-57-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to check if all elements in a given array are equal or not.
Next: Write a JavaScript program to split values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.