How do you add up all the values in an array?

M

Matt

How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
 
T

Terriblecow

It always depends on how eloquent you the answer to be, cause there are
a ton of ways to "add up all the values in an arary".

One of the most simple ways to do this involves a for loop. Depending
on your experience with javascript this may be a cake walk for you.

so here goes .. .

<script type="text/javascript">
<!--
// here you're gonna replace this array definition with your variable
length array

var ary = new Array(1,45,2,3,156,22);
// this is the variable that will store the result of your summation
var result = 0;
// here we will add each element in the array to the result variable
one ata time.
for (var i = 0; i< ary.length; i++) {
result += ary;
}

// this is the finished result.
alert(result);
//-->
</script>

But your question was pretty vague.
 
K

kaeli

How do you add up all the values in an array? The length of the array
is variable.

You loop through it and add them.
Don't forget to parseInt or parseFloat, just in case and check NaN (boolean
isNaN -- not a number). You might even want to employ regular expressions if
the data is entered by a user, since JS will often find a way to convert
things to numbers that really aren't numbers in the sense you expect.
Example: dates.

There is a length property to tell you the size. Loop 0 to length-1. Arrays
are 0-based (indexes) in JS.
Is there a built in function?
No.
In javascript, arrays are actually not like, say, Java or C. They can be
dynamically sized and they can contain more than one data type. They are
closer to ArrayList or Vector (java) or structs with pointers (C). So there
is no method to add because nothing stops you from putting strings and even
other arrays in there.

--
 
R

RobB

Matt said:
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?

There is now.

<script type="text/javascript">

Array.prototype.addNumbers = function(inclStrs)
{
var re = new RegExp(inclStrs ? '((number)|(string))':'number');
for (var i = 0,
l = this.length,
sum = 0,
n;
i < l;
++i)
{
if (re.test(typeof (n = this)))
sum += (!inclStrs) ? n :
/^[0-9]+$/.test(n) ? Number(n) : 0;
}
return sum;
}

var x = [ 1, 2, 'foo', 3, '100', 4, true, function(){j=2} ];
alert(x.addNumbers());
alert(x.addNumbers(true)); //include string digits
alert([ 100, '200', 300, '400', 0, '0' ].addNumbers(true));

</script>
 
R

RobB

Thx as always to the morons at google for inserting an illegal
character (right here: ((number)|(string))':'number'­ <-------)

Ruined every posting recently. Sorry, moving to a real newsreader....
 
R

rh

RobB said:
Matt said:
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?

There is now.

<script type="text/javascript">

Array.prototype.addNumbers = function(inclStrs)
{
var re = new RegExp(inclStrs ? '((number)|(string))':'number');
for (var i = 0,
l = this.length,
sum = 0,
n;
i < l;
++i)
{
if (re.test(typeof (n = this)))
sum += (!inclStrs) ? n :
/^[0-9]+$/.test(n) ? Number(n) : 0;
}
return sum;
}

</script>

When including strings, it might be a little surprising to find that
array values such as '1.333' or '-5' would fail to be included in the
total.

The prototype function would perhaps better be written as:

Array.prototype.addNumbers = function(inclStrs) {
var inclTypes = { 'number': true, 'string': inclStrs };
var sum=0, k = this.length;
while (k--) sum += inclTypes[typeof this[k]] && +this[k] || 0;
return sum;
}

where it would be more accommodating in the scope of the numbers
accepted in string form, and should prove to be considerably faster.

../rh
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Fri, 18 Mar 2005 10:02:32, seen in Matt
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?

No, but it is easy enough for the usual case.

For an array containing a Number in each position - an ordinary number
such as 3 or -4 or 5.67 or 1.234e5 - it's easy enough to write the code
each time, and any of these will do:

Tot = 0 ; for (J=0 ; J<A.length ; J++) Tot += A[J]

for (J=0, Tot=0 ; J<A.length ; J++) Tot += A[J]

Tot = 0 ; J = A.length ; while (J--) Tot += A[J]

The first is probably the most obvious, the last is probably the
fastest. If arrays are to be summed in that manner in many places in
the code, then it is worth making a function or method to do it.

If there is a possibility that some or all of the array entries are in
fact strings each representing a number in an obvious fashion, then
instead of Tot += A[J] one can use Tot += +A[J] .

If there is a possibility that any of the entries may be absent - not
zero, but missing, as in A = [1,,3] as opposed to A=[1,2,3] -
then *you* must decide what that represents. Is it right to skip the
missing entry as if it had not been there, or to treat it as present and
equal to zero (consequences differ if calculating an average), or to
consider that as an error needing to be reported? THE PROGRAMMER MUST
DECIDE - or be told ; it should not be left at the whim of someone
providing a "general" routine.

Similarly if there is a possibility that any of the entries is
definitely non-numeric, as in [1, "banana", 3].

Then an entry can be convertible to a number :
D = new Date("1970/01/02 00:00:00 GMT")
A = [1, D, 2]
for which Tot += A[J] gives "2Fri Jan 2 00:00:00 UTC 19701" and
Tot += +A[J] gives 86400003 ; IMHO, common sense suggests a
probable programming error.


Eschew rampant genericity.
 
R

rh

Dr said:
JRS: In article <[email protected]>, dated
Fri, 18 Mar 2005 10:02:32, seen in Matt
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?

No, but it is easy enough for the usual case.

For an array containing a Number in each position - an ordinary number
such as 3 or -4 or 5.67 or 1.234e5 - it's easy enough to write the code
each time, and any of these will do:

Tot = 0 ; for (J=0 ; J<A.length ; J++) Tot += A[J]

for (J=0, Tot=0 ; J<A.length ; J++) Tot += A[J]

Tot = 0 ; J = A.length ; while (J--) Tot += A[J]

The first is probably the most obvious, the last is probably the
fastest. If arrays are to be summed in that manner in many places in
the code, then it is worth making a function or method to do it.

Good advice, although I believe demonstration code should always
include variable declaration, even when assuming the global
environment.

Another possible in-line example whould be:

for (var tot=0, k=a.length; k--;) tot += a[k];

If there is a possibility that some or all of the array entries are in
fact strings each representing a number in an obvious fashion, then
instead of Tot += A[J] one can use Tot += +A[J] .

If there is a possibility that any of the entries may be absent - not
zero, but missing, as in A = [1,,3] as opposed to A=[1,2,3] -
then *you* must decide what that represents. Is it right to skip the
missing entry as if it had not been there, or to treat it as present and
equal to zero (consequences differ if calculating an average), or to
consider that as an error needing to be reported? THE PROGRAMMER MUST
DECIDE - or be told ; it should not be left at the whim of someone
providing a "general" routine.

In your example, the former array does not have a "missing" entry at
index 1. The value associated with index 1, which is in A, is
undefined. The following would have a missing entry at index 1:

var B = []; B[0] = 1, B[2] = 3;

You're correct that a determination (or declaration, or both) needs to
be made regarding the treatment of non-numerics. However, no-one,
including yourself, makes declarations of suitabilityof demonstration
code for any specific purpose. In general, the code, witin reasonable
bounds, meets the requirement specified by a poster asking for
assistance.

Eschew rampant genericity.

Eschew rampant pernicious pedantry.

../rh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top