'How do I calculateAverage?
I need to create a function in Javascript that is called calculateAverage which accepts arrays of numbers. The function should return the average in the array. If the array is empty, return 0.
I am new to coding and have only studied python.
int calculateAverage(int numbers_count, int* numbers) {
calculateAverage([50, 21, 80])
calculateAverage([30, 39, 58, 11])
calculateAverage([200])
calculateAverage([])
Solution 1:[1]
this can be a solution:
function calculateAverage(arr) {
const sum = arr.reduce((acc, curr) => acc + curr, 0)
return sum / arr.length
}
const arr = [5,10,1,5,20,50,30,25];
const average = calculateAverage(arr);
console.log(average)
Solution 2:[2]
you can do that like this...
function calculateAverage(arr) {
const rslt = arr.reduce((a, b) => a + b, 0) / arr.length;
return 0 === ~~rslt ? 0 : rslt;
}
console.log(calculateAverage([30, 39, 58, 11]));
Solution 3:[3]
You have to put your image in the folder man/figures and type such an Roxygen code:
#' \if{html}{Here is my figure:
#'
#' \out{<div style="text-align: center">}\figure{myfigure.png}{options: style="width:750px;max-width:75\%;"}\out{</div>}
#'
#' }
#' \if{latex}{Here is my figure:
#'
#' \out{\begin{center}}\figure{myfigure.png}\out{\end{center}}
#'
#' }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MarcoWriteCode |
| Solution 2 | Anas Abdullah Al |
| Solution 3 | Stéphane Laurent |
