I have a method in my Angular service/factory that accepts an array of arrays containing objects [[{},{}],[{},{}]]
as a parameter.
The parameter structure consists of arrays representing weeks, with each day's object containing a date and an integer value. For example, {"2017-01-10": 711}
.
The goal of the method is to combine each week's data into a single object while summing up the integer values. For instance,
{"name": "Week 1", "total": 3228}
How can I generate a name/label by extracting the first and last elements of each week array? This would result in an output like:
{"name": "Week 1 - 2017-01-10 to 2017-01-15", "total": 3228}
Below is the sample input passed to the method:
[
[
{
"2016-11-01": 319
},
{
"2016-11-02": 782
},
...
],
[
{
"2016-11-07": 319
},
{
"2016-11-08": 782
},
...
]
]
Here is the JavaScript method implementation:
function assignWeekNamesAndTotals(arrayOfWeeks) {
var data = arrayOfWeeks;
var result = data.reduce(function (previous, current, index) {
var total = current.reduce(function (sum, object) {
for (var key in object) {
sum += object[key]; // calculate total
}
return sum;
}, 0);
// Format the object as needed
var temp = {};
temp.name = "Week " + (index + 1);
temp.total = total;
previous.push(temp);
return previous;
}, [])
console.log("Assign Week names and Totals Output: " + JSON.stringify(result, null, " "));
return result;
}
Your help and advice on this matter are greatly appreciated!