1

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 " );
}

Here is the picture

nsuspect
  • 25
  • 2
  • You are not printing `sum` here: `console.log("The average of the values is " );`. Use `console.log("The average of the values is " +sum);` – Martin Apr 25 '21 at 16:33
  • 1
    @Martin - Hi, thanks for the solution, but I mean the sum I currently working on is being stringnify from the "document.getElementById("num").value ". So the result would just be 027102512, instead of 56 in total. That's where I stuck. – nsuspect Apr 25 '21 at 17:41

1 Answers1

1

Values of input elements are always strings. However, you can change them into numbers with parseInt().

myArray.push(parseInt(num));
Kinglish
  • 4,042
  • 2
  • 15
  • 27
  • 1
    They are always strings whether it's `type="number"` or not – adiga Apr 25 '21 at 16:59
  • @adiga - true, thanks. – Kinglish Apr 25 '21 at 17:14
  • @JohnTyner - Thanks John, I just fix my code following your solution, it's now working perfectly fine now. The course I am participating in, they do not mention anything about using "parseInt()" to convert DOM element to number in the theory. I guess I will have to read more documentation. Thank you. :)) – nsuspect Apr 25 '21 at 17:38
  • @nsuspect - another way to convert to a number is to place a plus sign right before it - as in `myArray.push(+num)` – Kinglish Apr 25 '21 at 17:46
  • @JohnTyner - Cool, interesting method, I'll give it try now, thanks again :)) – nsuspect Apr 25 '21 at 21:42