By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,776 Members | 1,233 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,776 IT Pros & Developers. It's quick & easy.

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

P: n/a
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
Jul 23 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
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[i];
}

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

But your question was pretty vague.

Jul 23 '05 #2

P: n/a
In article <31*************************@posting.google.com> ,
bi*******@gmail.com enlightened us with...
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.

--
--
~kaeli~
Join the Army, meet interesting people, kill them.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 23 '05 #3

P: n/a
Matt wrote:
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[i])))
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>

Jul 23 '05 #4

P: n/a
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....

Jul 23 '05 #5

P: n/a
rh
RobB wrote:
Matt wrote:
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[i])))
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

Jul 23 '05 #6

P: n/a
JRS: In article <31*************************@posting.google.com> , dated
Fri, 18 Mar 2005 10:02:32, seen in news:comp.lang.javascript, Matt
<bi*******@gmail.com> posted :
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.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7

P: n/a
rh
Dr John Stockton wrote:
JRS: In article <31*************************@posting.google.com> , dated Fri, 18 Mar 2005 10:02:32, seen in news:comp.lang.javascript, Matt
<bi*******@gmail.com> posted :
How do you add up all the values in an array? The length of the arrayis 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

Jul 23 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.