Chris Chris - 5 months ago 22
AngularJS Question

Create New Array from Existing Array Values With Unique and Sum

For some reason I'm stumbling to get the result I need with Javascript arrays.

I have rows of data which contain day, and several timestamps per row. What I need to do is transform that data to an array for chart.js, but merging rows by week, and summing the hours (from the timestamps). Below is where I am creating a new array from the query result, but am struggling to get it how I need it.

Here's where I create the array (with processing):

function chartData(queryrowlist){
var weeks = [];
angular.forEach(queryrowlist, function(value, key)
{
weeks.push(moment(value.date).format('w'),getOnHours(value),getOffHours(value))
});
// create chart array ...
return chart;
}


The weeks array ends up like this:

["23",28800000,3600000,"23",30300000,2700000,"24",35400000,3300000,"24",30000000,3300000]


Which is Week Number, OnHours, OffHours

The Week Number will be used as the Label, and the Hours as the On/Off Data in angular-chart/chart.js. The problem is all of the Week Numbers have to be Unique, and all of the Hours Summed up for each week.

So, I will need to output an array like this:

chart['weeks']=["23","24"]
chart['hours']=[[59100000,6300000],[65400000,6300000]]


This is probably simple, and it's just me hitting a thought wall... but if anyone has a solution, I'd be grateful.

Thank you in advance.

Update:

For anyone who might refer to this, the resulting array is incorrect for chart.js. Answers below are correct... as asked, I just asked the wrong thing and only realized after. Feeling like a fool :/

Chart.js want's all the line values in the same array, so instead of above example which is:

chart['weeks']=["23","24"]
chart['hours']=[[onhours,offhours],[onhours,offhours]]


It should be:

chart['weeks']=["23","24"]
chart['hours']=[[onhours,onhours],[offhours,offhours]]

Answer

Why not split into two arrays like you wanted?

function chartData(queryrowlist){
    // Set up our data store + return object
    var chart = {
        weeks: [],
        hours: []
    };
    // For every value in the parameter given
    angular.forEach(queryrowlist, function(value, key) {
        // Get the week, and check if it is in the array
        var week = moment(value.date).format('w');
        var weekIndex = chart.weeks.indexOf(week);

        // If the index is -1, it is not in the array, so just push values;
        if(weekIndex === -1) {
            chart.weeks.push(week);
            chart.hours.push([getOnHours(value),getOffHours(value)]);
        } else {

            // If the index is not, we assume that the weekIndex is the correct index to sum the values on.
            chart.hours[weekIndex] = [chart.hours[weekIndex][0] + getOnHours(value), chart.hours[weekIndex][1] + getOffHours(value)];
        }

    });
    return chart;
}