user188962
user188962

Reputation:

how to add array element values with javascript?

I am NOT talking about concatenating elements together, but adding their values to another separate variable.

Like this:

var TOTAL = 0;
for (i=0; i<myArray.length; i++) {
    TOTAL += myArray[i];
}

With this code, TOTAL doesn't add mathematically element values together, but it concatenates them next to each other, so if myArray[0] = "10" and myArray[1] = "10" then TOTAL will be "01010" instead of 20.

How should I write what I want?

Thanks

Upvotes: 1

Views: 14132

Answers (5)

zavidovych
zavidovych

Reputation: 4878

const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });

Upvotes: 4

JonH
JonH

Reputation: 33183

Use parseInt or parseFloat (for floating point)

var total = 0;
for (i=0; i<10; i++)
 total+=parseInt(myArray[i]);

Upvotes: 0

Greg
Greg

Reputation: 321864

A quick way is to use the unary plus operator to make them numeric:

var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
    TOTAL += +myArray[i];
}

Upvotes: 2

Pim Jager
Pim Jager

Reputation: 32129

Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)

var total = 0;
for(i=0; i<myArray.length; i++){
  var number = parseInt(myArray[i], 10);
  total += number;
}

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828200

Sounds like your array elements are Strings, try to convert them to Number when adding:

var total = 0;
for (var i=0; i<10; i++){
  total += +myArray[i];
}

Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.

Upvotes: 7

Related Questions