Search code examples
javascriptunderscore.jstime-seriesclick-tracking

Underscore do some calculation and return new object


I have a time series like this:

[
    {
        "_id": {
            "action": "click",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 5
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 13
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 25
    },
    {
        "_id": {
            "action": "click",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 7
    }
]

I need to do some calculation and return a similar object, in particular, I need to find the percentage between clicks and hits (clicks/hits*100 of the same date) returning an object like this:

[
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 38.46
    },
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 28
    }
]

Any hint?


Solution

  • _.groupBy(array, function(el){ return el._id.date; });
    

    The above would be how you can group, then you can map over that and calculate what you need. Example:

    http://jsfiddle.net/j9Htk/114/