Chris Chris - 1 year ago 107
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)
// create chart array ...
return chart;

The weeks array ends up like this:


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:


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.


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:


It should be:


Answer Source

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('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) {
        } 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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download