1

Here, I want to take inputs from users. Split and store them into array. Then show the summation of array numbers.

summation experiment

<!-- for taking inputs -->
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
<script type="text/javascript">

function seriesFunction()
{
    value = document.getElementById("seriesInput").value;
    // splitting string in an array
    value_arr = value.split(" ");
    alert(value_arr);
    // calling reduce method for summation
    var sum = value_arr.reduce(get_sum,0);
    // assigning result
    document.getElementById("sum").innerHTML =sum;
alert(sum);


    function get_sum(total, currentVal) {
total += currentVal;
return total;
}
}
</script>

Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
Ahmed Tareque
  • 161
  • 5
  • 17

2 Answers2

1

You are getting currentValue as string in the get_sum function, try making to integer. You can do it like:

function get_sum(total, currentVal) {
    currentVal = parseInt(currentVal);
    total += currentVal;
    return total;
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
DASH
  • 297
  • 1
  • 4
  • 10
  • DASH, you can't assume the numbers to be ints by using `parseInt`. OP says number. – Pankaj Shukla Jun 03 '17 at 20:30
  • I assumed that, he will understand the mistake ahmed was doing. You can use Number(currentVal) which will give you integer or float val whatever it is. By the +currentVal is the short hand way of doing thing. Thanks for point ting out. – DASH Jun 03 '17 at 20:34
  • No not required. – DASH Jun 03 '17 at 21:39
1

You need to modify the code to:

function get_sum(total, currentVal) {
                total += +currentVal;
                return total;
}

Notice + in front of currentVal. That will convert string to number not just int. So the benefit is that if you input three values like 1.1 1.2 1.3, you would get the sum as 6.6. Earlier without this you were doing string concatenation instead of sum that you intended to do.

function seriesFunction() {
  value = document.getElementById("seriesInput").value;
  // splitting string in an array
  value_arr = value.split(" ");
  alert(value_arr);
  // calling reduce method for summation
  var sum = value_arr.reduce(get_sum, 0);
  // assigning result
  document.getElementById("sum").innerHTML = sum;
  alert(sum);


  function get_sum(total, currentVal) {
    total += +currentVal;
    return total;
  }
}
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18