473,390 Members | 953 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

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

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
7 29113
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Bart Nessux | last post by:
The below code works well, except for the database insert. I want each element of the array to be inserted into the database, but only the last element of the array is inserted... all the elements...
9
by: dr. zoidberg | last post by:
Is it possible to put Variable in Array? Here is what I need: $array = Array($a,$b); $a = 'something'; $b = 'something else'; foreach ($array as $val) { echo "$val"; }
2
by: csx | last post by:
Hi all, Here's a simple problem I'm having problems with. How do I pass an array element to a function. For instance, values = new values(1, 1,'A',0); values = new values(2, 2,'B',1);...
20
by: Pavel Stehule | last post by:
Hello, Is possible merge two arrays like array + array => array select array_append(array, array); ERROR: function array_append(integer, integer) does not exist
5
by: Tom Cole | last post by:
Let's say I have the following JSON string returned from a server-side process: { values: } I then create a JSON object from it using eval() (tell me if this is not what should be done). ...
18
by: WilhelmAccess | last post by:
Hi, I am trying to automate the running of a SQL Query. I have a Table in Access 2003 that contains records with several fields, (member identifier, $ amount and months during the year they were...
15
by: Maarten | last post by:
I've found some answers to my problem on this forum, but not exactly the answer I was looking for. Sorry if I've missed something. This is my situation: I am trying to make an insertion into an...
5
by: Pukeko | last post by:
Hi, this is an array that is used for a dropdown menu. var imageArray = new Array( "ecwp://" + document.location.host + "/massey/images/massey/ massey_07_fullres.ecw", "ecwp://" +...
5
by: barcrofter | last post by:
I have two independent arrays and mysteriously they occupy the same space. Is this an error or a feature? Dim tokens$() '(input list of msn's and constants) Dim values() As...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.