I have defined a JavaScript variables called myData
which is a new Array
like this:
var myData = new Array([\'2013-01-22\', 0], [\'
Or in ES6
values.reduce((a, b) => a + b),
example:
[1,2,3].reduce((a, b)=>a+b) // return 6
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
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() };
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
I think the simplest way might be:
values.reduce(function(a, b){return a+b;})
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.