Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Ing
    Ing is offline
    New Coder
    Join Date
    Feb 2011
    Location
    Los Angeles
    Posts
    13
    Thanks
    10
    Thanked 0 Times in 0 Posts

    How to sum elements in an array?

    I tried the following code based on a post I saw somewhere else about summing all the elements of an array together. When I tried it though I couldn't seem to get it working. Can someone please point out what I did wrong or tell me a different way to sum array elements together? Thanks.
    Code:
    <script type="text/javascript">
    
    Array.prototype.sum = function() {
    for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]);
    return sum;
    }
    
    var myArray=[1,2,3,4,5];
    
    document.write(myArray.prototype.sum);
    
    </script>

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,366
    Thanks
    11
    Thanked 590 Times in 571 Posts
    it's fine code, but it is a function, so =you have to invoke it to use it:
    Code:
    alert(myArray.sum()) //shows: 15

    bonus: my version:
    Code:
    Array.prototype.sum = function() {
      return this.reduce(function(a,b){return a+b;});
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • Users who have thanked rnd me for this post:

    Ing (02-17-2011)

  • #3
    Ing
    Ing is offline
    New Coder
    Join Date
    Feb 2011
    Location
    Los Angeles
    Posts
    13
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by rnd me View Post
    bonus: my version:
    Code:
    Array.prototype.sum = function() {
      return this.reduce(function(a,b){return a+b;});
    }
    Thanks! Questions about your code:
    What do a and b represent?
    What does "reduce" do?

    I don't yet grasp what is taking place here.

  • #4
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    reduce is method of Array objects. It's available in alll mozilla's javascript and is not available in javascript of msie.

    a and b are arguments of the anonymous function passed as the arguments for the method reduce (it's usual phenomenon in javascript). Actually a is the current collected value and b is the current item of an array passed to this function.

    The code suggested by rnd me can be expanded as below:
    Code:
    Array.prototype.sum = function()
    {
        var a = this[0];
        for (var i = 1; i < this.length; i++) {
            a = a + this[i];
        }
        return a;
    };
    I intentionally highlighted the code there to demonstrate the part corresponding to the anonymous function in the rnd me's example.

    This method will return a sum of all items of array or undefined (or exception) if an array is empty like [ ].
    Last edited by siberia-man; 02-17-2011 at 08:55 AM.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,366
    Thanks
    11
    Thanked 590 Times in 571 Posts
    Quote Originally Posted by siberia-man View Post
    reduce is method of Array objects. It's available in alll mozilla's javascript and is not available in javascript of msie.
    it is now, and I made it old copies:
    Code:
    (function build(o){var M=Math;window.F={min:M.min,max:M.max};var it;if(o.pre){o.pre(F);delete o.pre;}for(i in o){it=o[i];it=it.join?it:[0,it];F[i]=Function(it[0]||"a",it[1].replace(/`([0-7])/g,function(b,a){return[":function(a,b){var t=this.concat(),m=t.length,i=","function","length","return ","this","concat","var ","a.call("][a]||a;}));}if(F.init){F.init(F);delete F.init;}}(({A:["o,l","if(o.charAt){o=o.split(o.match(/\\,/)?\",\":\"\");}\nif(o*0.1){`3F.S(Array(o)).split(\"\").map(F.fill,l!=null?l:\"\");}\n`6r=[],z;for(z in o){if(o.hasOwnProperty(z)){r.push(l?l(o[z]):o[z]);}}\n`3r"],F:["a,c","`6s=c||a;`3a.call?a:Function(c?a:\"a,b,c\",s.indexOf(\"`3\")!==-1?s:\"`3\"+s)"],If:"`3Function(\"a,b\",\"`3\"+a+\"?a:undefined\")",avg:["a,b,c","`4[0]+=a/c.`2;`6t=\"R\""],count:"`3`4[a]=`4[a]?`4[a]+1:1",bytypes:"`3typeof a==`4?1:0",equal:"`3a===`4",even:"`3a%2==0",extract:"`3a[`4]",fill:["a,b,c","`3`4.call?`4.apply(c,F.A(arguments)):`4"],gt:"`3a>`4",init:"`6o=Array.prototype,it,i,e={map`00,r=[];for(;i<m;i++){if(i in t){r[i]=`7b,t[i],i,t);}}`3r;},filter`00,r=[],g=0;for(;i<m;i++){if(i in t&&`7b,t[i],i,t)){r[g++]=t[i];}}`3r;},every`00;`3m&&t.filter(a,b).`2==m;},some`01;for(;m--;){if(m in t&&`7t,t[m],m,t)&&!--i){`3true;}}`3false;},lastIndexOf`0b||-1;for(;m>i;m--){if(m in t&&t[m]===a){`3l;}}`3-1;},indexOf`0b||0;for(;i<m;i++){if(i in t&&t[i]===a){`3i;}}`3-1;},reduce`00,r=b||t[i++];for(;i<m;i++){r=`7null,r,t[i],i,t);}`3r;},reduceRight`0m-1,r=b||t[i--];for(;i>-1;i--){r=`7null,r,t[i],i,t);}`3r;},forEach:`1(a,b){`4.`5().map(a,b);},clean`00,r=[],g=0,x,O;a=F.F(a||F.S);for(;i<m;i++){if(i in t&&(x=`7b,t[i],i,t))){r[g++]=x;}}`3arguments[2]?b:r;}};for(it in e){i=o[it];o[it]=i||e[it];}\"String,Number,RegExp,Boolean,Document\".split(\",\").map(F.F(\"F[a.slice(0,1)]=window[a]\"));F.I=`1(a){`3parseInt(a,10);}",invoke:"`3a[`4]()",isInt:"`3parseInt(a,10)===a",k:"`3a",keys:["o","`6r=[];o=o||F;for(z in o){if(o.hasOwnProperty(z)){r[r.`2]=z;}}\n`3r"],lt:"`3a<`4",match:"`3F.S(a).indexOf(`4)!==-1",not:"`3a!=`4",odd:"`3a%2!==0",ok:"`3a!=null",pre:"",run:"`3`4(a)",same:"`3a==`4",sum:["a,b","`3a+b"],tag:"`3\"<\"+`4+\">\"+a+\"</\"+`4+\">\"",times:"`3a*`4",unique:["a,b,c","`3c.lastIndexOf(a)==b?a:undefined"],zip:["a,b","`6it=[a];if(b in `4){it=it.`5(`4[b]);}\n`3it"]})));
    
    /////////////////////////////////////
    
    
    Array.prototype.sum = function() {
      return this.reduce(function(a,b){return a+b;});
    }
    
    var myArray=[1,2,3,4,5];
    
    
    alert(myArray.sum())
    tested in IE9 as IE7
    Last edited by rnd me; 02-17-2011 at 11:49 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #6
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    If you want to include IE8 users, and others who have older browsers, you can provide a rough equivilent for reduce.

    Code:
    if(!Array.prototype.reduce){
    	Array.prototype.reduce= function(fun, temp, scope){
    		var i= 0, T= this, len= T.length, temp;
    		if(typeof fun=== "function"){
    			if(temp==undefined)temp= T[i++];			
    			while(i < len){
    				if(i in T) temp= fun.call(scope, temp, T[i], i, T);
    				i++;
    			}
    		}
    		return temp;
    	}
    }
    // sample
    Code:
    var A= [1, 2, 3, 4, 5, 6, 7];
    A.reduce(function(a, b){return  a+b; });
    /*  returned value: (Number)28*/
    or if you have a mixed or sparse array, start with a known number (0)-
    Code:
    var A= [1, 2, 3, 4, 5, 6, 7];
    A.reduce(function(a, b){return a+(Number(b)||0);}, 0);
    I have to say it is simpler in this case to use ordinary methods-

    Code:
    var A=[1,2,3,4,5,6,7], L=A.length, i=0, n=0;
    while(i<L)n+=A[i++];
    alert(n)
    
    /*  returned value: (Number)
    28
    */
    Last edited by mrhoo; 02-17-2011 at 02:09 PM. Reason: force numbers and simplify initial value


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •