Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate the average of array elements in Javascript

I got this Javascript exercise. The average should be 11.2, but my program returned 5420502.4.


Define an empty array. Also create two functions:

addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.


var arr = [];

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(num);
}

function printInfo() {
    var len = arr.length;
    console.log("The array has " + len + " elements.");
    
    var total = 0;
    for (var i = 0; i < len; i++) {
        total += arr[i]; // replace arr[i] with +arr[i]
    }
    var avg = total / len;
  // additionally render result to UI
  document.getElementById("info").innerText = avg;
    return console.log("The average of the values is " + avg);
}
.outerStyle { border: 2px solid black; width: 45%; }
.inpStyle { padding: 10px; margin: 10px; }
button { margin: 10px; }
<div id="outer" class="outerStyle">
  <div class="inpStyle">
    <label for="num">Enter number: </label>
    <input id="num" type="number" />
  </div>
  <button id="addBtn" onclick="addNumber()">Add</button>
  <button id="printInfo" onClick="printInfo()">Print Info</button>
  <hr/>
  <div id="info" />
</div>

>Solution :

The value from your input is a string. So, it will concatenate in to total. If your input value was 1 and you added it to the array twice, your array would consist of 2 strings, "1" and "1". Then, you’re adding this, which makes "11" because you’re adding strings together.

You’ll want to use something like parseInt to convert the string to a number first.

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(parseInt(num));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading