Sum of values in an array using jQuery

I have an array containing some values and I want to get their sum. Here is the example:

var somearray = ["20","40","80","400"];

I want to sum these values using jQuery. In this example the result would be 540.

Jquery using map to sum array

My values array is returning correctly in the form of [100,200,300,500] I just wish to sum up these values, what am I doing wrong? Jquery $(‘select’).focus(function () { previous = parseInt($(this).va

Get Sum of Values using array_combine?

I am trying to count the total sum of values using array_combine. I have the duplicate key also, for example i have the array of emailid and array of product price. $data1 = array([email protected]

Sum values of array using zip

i have array of arrays this way. I wanna sum a specific fild (like 3rd in the list ) data = [[d, 408.56087701, 87.26907024], [b, 277.95015117, 75.19386881], [b, 385.41416264, 84.73488504], [b, 380.316

Sum array values

I’m making a shipping service app to Shopify and my callback URL have this JSON post using json_decode to make an array. The value I want to sum is grams and putting into variable and then compare wit

sum all values from array

I need to sum all the values from my array, so here is an example of it: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 4 [5] => 6 [6] => 6 ) looking a way to sum all from sa

Calculate the sum of values in an array using renderscript

Hi I am a newbie and trying to code in Renderscript. I would want to know how can I perform a sum of elements in an array using render script. Is there a way I can pass the output back into the script

Trying to get sum of array values

I got this array and I am trying to make a sum of the [za] values but without any success. My last try was this code: foreach ( $sumza as $sumzakey ) { $sum += $sumza[$sumzakey][‘za’]; } Array ( [0] =

Sum values ​​using each()

I’m trying to return the sum of values ​​every time one of the select is changed. But the sum is always wrong: $(‘select’).change(function () { a = 0; $(‘select’).each(function () { a += parseInt($(‘o

how to write array of values sum of digits it self a number in c# without using linq concept

I have values like below int[] arr1 = new int[] {25, 47, 60,98};// Not Exactly so how to write Sum of digits itself a number using array values of each number. 2.Total values Sum of digits itself

sum input values using datejs

I am trying to grab input fields values, convert them to milliseconds, sum them all. How can I sum hours using datejs ? eg. <input type=text class=singleSumma value=03:30> <input type=

Answers

You don’t need jQuery. You can do this using a for loop:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

var total = 0;
$.each(someArray,function() {
    total += parseInt(this, 10);
});

To also handle floating point numbers:

  • Standard JavaScript:

    var arr = ["20.0","40.1","80.2","400.3"];
    var n   = arr.length;
    var sum = 0;
    while(n--)
       sum += parseFloat(arr[n]) || 0;
    
  • jQuery:

    var arr = ["20.0","40.1","80.2","400.3"];
    var sum = 0;
    $.each(arr,function(){sum+=parseFloat(this) || 0;});
    

What the above gets you:

  • ability to input any kind of value into the array; number or numeric string(123 or “123”), floating point string or number (“123.4” or 123.4), or even text (abc)
  • only adds the valid numbers and/or numeric strings, neglecting any bare text (eg [1,’a’,’2′] sums to 3)

If you want it to be a jquery method, you can do it like this :

$.sum = function(arr) {
    var r = 0;
    $.each(arr, function(i, v) {
        r += v;
    });
    return r;
}

and call it like this :

var sum = $.sum(["20", "40", "80", "400"]);

You can use reduce which works in all browser except IE8 and lower.

["20","40","80","400"].reduce(function(a, b) {
    return parseInt(a, 10) + parseInt(b, 10);
})

Another method, if eval is safe & fast :

eval(["10","20","30","40","50"].join("+"))

In http://bugs.jquery.com/ticket/1886 it becomes obvious that the jQuery devs have serious mental issues reg. functional programming inspired additions. Somehow it’s good to have some fundamental things (like map) but not others (like reduce), unless it reduces jQuery’s overall filesize. Go figure.

Helpfully, someone placed code to use the normal reduce function for jQuery arrays:

$.fn.reduce = [].reduce;

Now we can use a simple reduce function to create a summation:

//where X is a jQuery array
X.reduce(function(a,b){ return a + b; });
// (change "a" into parseFloat("a") if the first a is a string)

Lastly, as some older browsers hadn’t yet implemented reduce, a polyfill can be taken from MDN (it’s big but I guess it has the exact same behavior, which is desirable):

if ( 'function' !== typeof Array.prototype.reduce ) {
    Array.prototype.reduce = function( callback /*, initialValue*/ ) {
        'use strict';
        if ( null === this || 'undefined' === typeof this ) {
          throw new TypeError(
             'Array.prototype.reduce called on null or undefined' );
        }
        if ( 'function' !== typeof callback ) {
          throw new TypeError( callback + ' is not a function' );
        }
        var t = Object( this ), len = t.length >>> 0, k = 0, value;
        if ( arguments.length >= 2 ) {
          value = arguments[1];
        } else {
          while ( k < len && ! k in t ) k++; 
          if ( k >= len )
            throw new TypeError('Reduce of empty array with no initial value');
          value = t[ k++ ];
        }
        for ( ; k < len ; k++ ) {
          if ( k in t ) {
             value = callback( value, t[k], k, t );
          }
        }
        return value;
      };
    }
    var arr = ["20.0","40.1","80.2","400.3"],
    sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });

Worked perfectly for what i needed. Thanks vol7ron

You can do it in this way.

var somearray = ["20","40","80","400"];

somearray = somearray.map(Number);

var total = somearray.reduce(function(a,b){  return a+b })

console.log(total);