Skip to content Skip to sidebar Skip to footer

Underscore Sortby, Groupby With Count Of Grouped Arrays

I'm having a bit of trouble manipulating an array of objects using underscore. I am almost there but have got stuck on attempting to combine countBy within the underscore chain.

Solution 1:

You need to set the count after the groupBy, but before the first map completes, because in that map you're returning only one record.

I've modified the fiddle: https://jsfiddle.net/xsfs0ua0/1/

Here's the relevant change:

var selectedMessages = _.chain(messages)
    .sortBy('dateOfMessage')
    .reverse()
    .groupBy('messageHeaderId')
    .map(function(a) {
        // since returning only a[0], assign a new property 'count' with the size of the array
        a[0]['count'] = _.size(a);
        return a[0];
    })
    .map(function(b){...})
    .value();

Post a Comment for "Underscore Sortby, Groupby With Count Of Grouped Arrays"