views:

54

answers:

1

Hi folks,

I'm trying to create a histogram in flot, where the bars are organized by day.

I cannot find a way to merge values into 1 bar per day.

__

Any ideas?

+1  A: 

There might be things to your question that are flot-specific, in which case I might have missed out on them. But if you've just got a javascript data structure with dates, and want to aggregate them into full days, you could do something like this.

Assume the following data source:

var data = [];
data.push({ value: 4, date: new Date(1278940338413) }); // july 12, 15:12:18
data.push({ value: 7, date: new Date(1278340738313) }); // july 5, 16:38:58
data.push({ value: 2, date: new Date(1278940331313) }); // july 12, 15:12:11

You can then write a function like this one to parse your data structure into a new format:

function aggregateByDate(source) {
    var aggregateHash = {};

    for(var i = 0; i < source.length; i++) {
    var item = source[i];
        var compareString = item.date.getFullYear() + '-' + (item.date.getMonth()+1) + '-' + item.date.getDate();

        if(!(compareString in aggregateHash)) {
           aggregateHash[compareString] = [];
        }

        aggregateHash[compareString].push(item);
    }

    var newSource = [];
    for(var key in aggregateHash) {

       var sum = 0;

       for(var i = 0; i < aggregateHash[key].length; i++) {
          sum += aggregateHash[key][i].value;
       }

       newSource.push({
          total: sum,
          count: aggregateHash[key].length,
          items: aggregateHash[key],
          dateString: key
       });
    }

    return newSource;
}

It'll give you the following result:

/*
   INPUT:
   [
    { value: 4, date: ( july 12, 15:12:18 ) },
    { value: 7, date: ( july 5, 16:38:58 ) },
    { value: 2, date: ( july 12, 15:12:11 ) }
   ]
*/

var output = aggregateByDate(data);

/*
   OUTPUT:
   [
     { count: 2, dateString: '2010-7-12', items: Array(2), total: 6 },
     { count: 1, dateString: '2010-7-5', items: Array(1), total: 7 }
   ]
*/

What it does is to create a hash with what is represented in the output as dateString for a key, and it iterates over the source collection to populate this hash with arrays for each hash key. After that, it iterates all the keys in the hash, and creates an array of objects containing the result of the hashed group.

David Hedlund