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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matt

    #1

    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?
  • Terriblecow

    #2
    Re: How do you add up all the values in an array?

    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.

    Comment

    • kaeli

      #3
      Re: How do you add up all the values in an array?

      In article <319e2491.05031 81002.9bb3c4f@p osting.google.c om>,
      bigoxygen@gmail .com enlightened us with...[color=blue]
      > How do you add up all the values in an array? The length of the array
      > is variable.[/color]

      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.
      [color=blue]
      > Is there a built in function?[/color]
      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.



      Comment

      • RobB

        #4
        Re: How do you add up all the values in an array?

        Matt wrote:[color=blue]
        > How do you add up all the values in an array? The length of the array
        > is variable. Is there a built in function?[/color]

        There is now.

        <script type="text/javascript">

        Array.prototype .addNumbers = function(inclSt rs)
        {
        var re = new RegExp(inclStrs ? '((number)|(str ing))':'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.addNumb ers());
        alert(x.addNumb ers(true)); //include string digits
        alert([ 100, '200', 300, '400', 0, '0' ].addNumbers(tru e));

        </script>

        Comment

        • RobB

          #5
          Re: How do you add up all the values in an array?

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

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

          Comment

          • rh

            #6
            Re: How do you add up all the values in an array?

            RobB wrote:[color=blue]
            > Matt wrote:[color=green]
            > > How do you add up all the values in an array? The length of the[/color][/color]
            array[color=blue][color=green]
            > > is variable. Is there a built in function?[/color]
            >
            > There is now.
            >
            > <script type="text/javascript">
            >
            > Array.prototype .addNumbers = function(inclSt rs)
            > {
            > var re = new RegExp(inclStrs ? '((number)|(str ing))':'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;
            > }[/color]
            <..>[color=blue]
            > </script>[/color]

            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(inclSt rs) {
            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

            Comment

            • Dr John Stockton

              #7
              Re: How do you add up all the values in an array?

              JRS: In article <319e2491.05031 81002.9bb3c4f@p osting.google.c om>, dated
              Fri, 18 Mar 2005 10:02:32, seen in news:comp.lang. javascript, Matt
              <bigoxygen@gmai l.com> posted :
              [color=blue]
              >How do you add up all the values in an array? The length of the array
              >is variable. Is there a built in function?[/color]

              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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              • rh

                #8
                Re: How do you add up all the values in an array?

                Dr John Stockton wrote:[color=blue]
                > JRS: In article <319e2491.05031 81002.9bb3c4f@p osting.google.c om>,[/color]
                dated[color=blue]
                > Fri, 18 Mar 2005 10:02:32, seen in news:comp.lang. javascript, Matt
                > <bigoxygen@gmai l.com> posted :
                >[color=green]
                > >How do you add up all the values in an array? The length of the[/color][/color]
                array[color=blue][color=green]
                > >is variable. Is there a built in function?[/color]
                >
                > No, but it is easy enough for the usual case.
                >
                > For an array containing a Number in each position - an ordinary[/color]
                number[color=blue]
                > such as 3 or -4 or 5.67 or 1.234e5 - it's easy enough to write the[/color]
                code[color=blue]
                > 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.
                >[/color]

                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];

                [color=blue]
                > If there is a possibility that some or all of the array entries are[/color]
                in[color=blue]
                > 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[/color]
                and[color=blue]
                > equal to zero (consequences differ if calculating an average), or to
                > consider that as an error needing to be reported? THE PROGRAMMER[/color]
                MUST[color=blue]
                > DECIDE - or be told ; it should not be left at the whim of someone
                > providing a "general" routine.
                >[/color]

                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.

                <..>
                [color=blue]
                > Eschew rampant genericity.
                >[/color]

                Eschew rampant pernicious pedantry.

                ../rh

                Comment

                Working...