'How to find mean of an array using Javascript [duplicate]

I tried to iterate through the array and print the sum. But the output am getting is elements of the array.

 <p id="ans"></p>

    <script>
      var text = "the mean is ";
      function mean() {
        var sum = 0;
        var input = document.getElementsByName("values");
        for (var i = 0; i < input.length; i++) {
          sum += input[i].value;
          text = text + sum;
        }

        document.getElementById("ans").innerHTML = text;
      }
    </script>


Solution 1:[1]

Parse the string values into integers and then sum it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt This is because in javascript if you adding a number to a string it will be casted to a string. For example:

0 + '1' + '2' // 012

But with parse int:

0 + parseInt('1') + parseInt('2') // 3

Or you can cast to int with a simple plus also:

0 + (+'1') + (+'2') // 3

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