Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Daniela costina Vaduva Avatar asked Apr 17 '13 10:04

Daniela costina Vaduva


3 Answers

You could use the Array.reduce method:

const myData = [
  ['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]
];
const sum = myData
  .map( v => v[1] )                                
  .reduce( (sum, current) => sum + current, 0 );
  
console.log(sum);

See MDN

like image 181
KooiInc Avatar answered Nov 12 '22 14:11

KooiInc


I think the simplest way might be:

values.reduce(function(a, b){return a+b;})
like image 31
ruhanbidart Avatar answered Nov 12 '22 13:11

ruhanbidart


Try the following

var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];

var myTotal = 0;  // Variable to hold your total

for(var i = 0, len = myData.length; i < len; i++) {
    myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up
}

document.write(myTotal); // 22 in this instance
like image 18
Mark Walters Avatar answered Nov 12 '22 13:11

Mark Walters