0

I have a data like this:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100},
    {date: "2010-02-09", total: 300}
];

I want to create a grouped and sum of total like this.

var grouped = [
    {date: "2000", total: 220}, 
    {date: "2010", total: 100}
];

I am using underscorejs but did not find function.

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();

    return {date: year, total: item.total}; 
});

workig code is here.

2 Answers 2

1

Using the reduce function. I see this has been jst answered before i could post. But just spent time coding it. So posting it here anyways. Btw this answer uses chaining.

var byYear = _.chain(dates)
            .map(function(item){ 
                var year = new Date(Date.parse(item.date)).getFullYear();
                return {date: year, total: item.total}; 
            })
            .groupBy('date')
            .map(function (value,key) { 
                            var reduceVal = _.reduce(value, function (acc, val)
                                                            { 
                                                                return acc + val.total;
                                                            },0 ); 
                            return {'year':key,'total' :reduceVal};
                })
            .value();


alert(JSON.stringify(byYear));
Sign up to request clarification or add additional context in comments.

Comments

1

I believe you are looking for the reduce function:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100}
];

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();        
    return {date: year, total: item.total}; 
});

var grouped = _.reduce(byYear, function(memo, item) {
    memo[item.date] = (memo[item.date] || 0) + item.total;
    return memo;
}, {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.