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?
Creating a sum method would work nicely, e.g. you could add the sum function to Array
then you could do
and in your case
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) {
thenthis
would becomearr
Or in ES6
values.reduce((a, b) => a + b),
example:
Try the following
Old way (if you don't now the length of arguments/parameters)
ES6 (destructuring of array)
You can use the native map method for Arrays. map Method (Array) (JavaScript)
a is your result
I would use reduce
Available on jsfiddle