[javascript] Sum values from an array of key-value pairs in JavaScript

I have defined a JavaScript variables called myData which is a new Array like this:

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

I am wondering if it is possible to sum the number values found in the array (ex. 0+0+21+2+0 and so on) and have probably a variable with the result that I can use outside of the script tag because I have 7 of this kind of arrays corresponding for each of the day in the week. I want to make a comparison afterwards based on that. That is the most preferred method for this kind of actions if is possible?

This question is related to javascript arrays for-loop sum

The answer is


The javascript built-in reduce for Arrays is not a standard, but you can use underscore.js:

var data = _.range(10);
var sum = _(data).reduce(function(memo, i) {return memo + i});

which becomes

var sumMyData = _(myData).reduce(function(memo, i) {return memo + i[1]}, 0);

for your case. Have a look at this fiddle also.


You can use the native map method for Arrays. map Method (Array) (JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result


If you want to discard the array at the same time as summing, you could do (say, stack is the array):

var stack = [1,2,3],
    sum = 0;
while(stack.length > 0) { sum += stack.pop() };

Or in ES6

values.reduce((a, b) => a + b),

example:

[1,2,3].reduce((a, b)=>a+b) // return 6

I would use reduce

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle


where 0 is initial value

Array.reduce((currentValue, value) => currentValue +value,0)

or

Array.reduce((currentValue, value) =>{ return currentValue +value},0)

or

[1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)

You could use the Array.reduce method:

_x000D_
_x000D_
const myData = [_x000D_
  ['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],_x000D_
  ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], _x000D_
  ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], _x000D_
  ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]_x000D_
];_x000D_
const sum = myData_x000D_
  .map( v => v[1] )                                _x000D_
  .reduce( (sum, current) => sum + current, 0 );_x000D_
  _x000D_
console.log(sum);
_x000D_
_x000D_
_x000D_

See MDN


I think the simplest way might be:

values.reduce(function(a, b){return a+b;})

Creating a sum method would work nicely, e.g. you could add the sum function to Array

Array.prototype.sum = function(selector) {
    if (typeof selector !== 'function') {
        selector = function(item) {
            return item;
        }
    }
    var sum = 0;
    for (var i = 0; i < this.length; i++) {
        sum += parseFloat(selector(this[i]));
    }
    return sum;
};

then you could do

> [1,2,3].sum()
6

and in your case

> myData.sum(function(item) { return item[1]; });
23

Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like. that could mean changing the signature to myModule.sum = function(arr, selector) { then this would become arr


Old way (if you don't now the length of arguments/parameters)

 >> function sumla1(){

    result=0
    for(let i=0; i<arguments.length;i++){

        result+=arguments[i];

    }
    return result;
    }
    >> sumla1(45,67,88);
    >> 200

ES6 (destructuring of array)

>> function sumla2(...x){return x.reduce((a,b)=>a+b)}
>>
>> sumla2(5,5,6,7,8)
>>
>> 31
>>
>> var numbers = [4, 9, 16, 25];
>> sumla2(...numbers);
>> 54

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to sum

Iterating over arrays in Python 3 Get total of Pandas column Pandas: sum DataFrame rows for given columns How to find sum of several integers input by user using do/while, While statement or For statement SQL Sum Multiple rows into one Python Pandas counting and summing specific conditions SELECT query with CASE condition and SUM() Using SUMIFS with multiple AND OR conditions How to SUM parts of a column which have same text value in different column in the same row how to count the total number of lines in a text file using python