Dianna Dianna - 29 days ago 5
Javascript Question

How to find the sum of arrays entered by user?

How do I find the sum of the numbers entered by the user in the numbersBox?
If the user entered "5, 3, 6, 1" in the numbersBox, I should be getting the answer "15" in the sumBox after clicking the "Find Sum" button. I cannot figure out how to add up all the array elements and what should I be putting in the for loop.

function findSUM(){
list = numbersBox.value.split(",");

var sum = list[0];
for(var i = 0; i < list.length; i++){
list[i] = parseInt(list[i]);

if(list[i] < i){
max += list[i];
}
}
sumBox.value = sum;
}





<label>Write numbers separated by commas:</label>
<br><br>
<input type="text" id="numbersBox" />

<label>Sum of all numbers:</label>

<input type="text" id="sumBox" />

<button type="button" onclick="findSUM();">Find Sum</button>


Thank you. I will really appreciate all your help.

Answer

You need to converts all array elements to Number here Array.prototype.map() can be used. Iteration should start with 2nd index as variable sum is initialized with value if number at first index.

function findSUM() {
  //Create a list of Numbers
  var list = document.getElementById('numbersBox').value
    .split(",")
    .map(function(x) {
      return isNaN(x) ? 0 : Number(x);
    });

  //Init with first no
  var sum = list[0];

  //Iteration starts wit 2nd element
  for (var i = 1; i < list.length; i++) {
    sum += list[i];
  }
  document.getElementById('sumBox').value = sum;
}
<label>Write numbers separated by commas:</label>
<br>
<br>
<input type="text" id="numbersBox" />
<label>Sum of all numbers:</label>
<input type="text" id="sumBox" />
<button type="button" onclick="findSUM();">Find Sum</button>

Comments