-3

enter image description here

Hi, I just learnt about Javascript Functions and would like to know the method for finding out average using Arrays and Functions in JS. I have linked a screenshot of my code, can you please help me?

SakarJ_08
  • 1
  • 1
  • 2
    [Please see why we shouldn't post images of text :)](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Dave Newton Aug 24 '21 at 17:45
  • Please see the [How to Ask](https://stackoverflow.com/help/how-to-ask) page. What's the specific issue(s)? How to calculate an average? How to sum values in an array? How to find the length of an array? How to divide? (Yes, this is a hint.) – Dave Newton Aug 24 '21 at 17:46
  • Does this answer your question? [Finding the average of an array using JS](https://stackoverflow.com/questions/29544371/finding-the-average-of-an-array-using-js) – Shiraz Chokshi Aug 24 '21 at 17:47
  • See [this](https://stackoverflow.com/a/41452260/3674619) answer using ES6 and reduce: – Shiraz Chokshi Aug 24 '21 at 17:48
  • 4
    Your "code" is just... `return`. That's not a valid attempt in my book. – Niet the Dark Absol Aug 24 '21 at 17:55

1 Answers1

-1

const scores = [60, 75, 21, 43];
const avg = scores.reduce((accumulator, currentValue) => accumulator + currentValue)/scores.length;
console.log(avg);

The Reduce function when used on an array will iterate over its entirety, with each iteration having access to a Accumulator (A single variable shared across all iterations) and a CurrentValue (Represents the current interation value). Using this you can add all the values together and divide the result by the array's length.

This can also be replaced with a function, "(accumulator, currentValue) => ..." is a lambda expression and is basically just shorthand for "function funcNameHere(accumulator, currentValue) { ... }"

Lambda expressions can also declare a body just like a normal function. "(param) => { ... }"

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gavin
  • 114
  • 1
  • 1
  • 8
  • 1
    YMMV, but I believe (a) if there are multiple duplicates, (b) the OP didn't make an attempt to solve the problem, and (c) the OP doesn't describe the specific issue(s) they're having, an answer isn't super-appropriate. – Dave Newton Aug 24 '21 at 17:57
  • Yes, rules are rules. Just giving a break considering they are brand new to this and trying not to discourage someone just learning for the first time. Mistakes will be made. – Gavin Aug 24 '21 at 17:59