Friday, June 11, 2021

Javascript Practice 75: JS Hero - Functions call functions

 
Question: 

Write a function sum that takes an array of numbers and returns the sum of these numbers. Write a function mean that takes an array of numbers and returns the average of these numbers. The mean function should use the sum function.




Answer: 

function sum (arr) {

let totalSum = arr.reduce((acc,cv) => acc + cv);

return  totalSum; 

}; 

function mean (arr) {

let meanVal = sum(arr) / arr.length;

return meanVal;

}; 




> we declare a function 'sum'
> it has one parameter 'arr' 
> we declare a variable 'totalSum' 
> we use the reduce method to reduce the value in the array to 1 unit
> we also want to add each and every element of the array
> we use the accumulator and the current value to do that 
> it works like a snow ball, keeps accumulating the values from left to right in an array
> this accumulated amount gets stored in the 'totalSum' variable
> we then return the 'totalSum' variable at the end of the 'sum' function 
> we then declare another function 'mean' 
> it has one parameter 'arr' 
> we declare a variable 'meanVal' 
> we want to store the mean value / average of the numbers in an array in the 'meanVal' variable
> to get the average of the numbers, we need to add the numbers and divide it with the total numbers
> like this: 2 + 4 + 6 + 8 = 20; 20 / 4 = 5;
> in order to get the sum of all the elements in an array, we can use the function 'sum' that we created in this function 'mean' 
> like this: sum(arr)
> we then need to divide this number with the total number of elements in the array
> like this: sum(arr) / arr.length
> we store the result in the variable 'meanVal' 
> we return the variable 'meanVal' to get our answer

No comments:

Post a Comment