Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the sum of an array in javascript [duplicate]

Tags:

javascript

I have to write 6 small JavaScript scripts for school and I've got them all working apart from this one.

function calculate() {
    var numbers = [
        document.getElementById("num_one").value ,
        document.getElementById("num_two").value ,
        document.getElementById("num_three").value 
    ];
    var sum = numbers[0] + numbers[1] + numbers[2];
    document.getElementById("display_sum").innerHTML = sum;
}

The user is supposed to enter 3 numbers click a button and it should add them all togther or "find the sum".

My Problem is, it just joins the numbers togther instead of adding them. Does anyone know a way to fix this?

like image 527
Craig Harkins Avatar asked Nov 12 '15 11:11

Craig Harkins


People also ask

How do you find the repeating value in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


1 Answers

You are "summing" string variables so Javascript is concatenating them.

You need to convert them to numbers in order to have an arithmetic sum:

function calculate() {
        var numbers = [
            document.getElementById("num_one").value ,
            document.getElementById("num_two").value ,
            document.getElementById("num_three").value 
        ];
        var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
        document.getElementById("display_sum").innerHTML = sum;
        }
like image 135
Juan Avatar answered Sep 27 '22 22:09

Juan