I just started to learn Javascript and have a question about finding the sum of an array. The threads require like this:
"Define an empty array. Also create two functions: 1/ addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array. 2/ printInfo() outputs the amount of elements in the array to the console, then the average of their values. The HTML document has two buttons for calling the functions. "
I was able to make it to the part where I can find the total element in the array, but when I try to calculate the sum of this array, using reduce() method. But somehow the result shows as a string of each element being joint together, but not as a final number. The sum of this array should be the sum of 2 + 7 + 10 + 12 + 25 = 56
var myArray = [];
function addNumber(){
var num = document.getElementById("num").value;
myArray.push(num);
}
function printInfo(){
var arr=myArray;
var array=myArray.length;
var sum = arr.reduce(function(a, b){return a + b;}, 0);
console.log(sum);
console.log("The array has " + array + " elements.");
console.log("The average of the values is " );
}