Egor Malkevich Egor Malkevich - 11 days ago 6
Javascript Question

How to do group by filter in Aurelia

I'm looking way to do something like

JS

$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];


HTML:

<ul repeat.for="obj of players | groupBy: 'team'">
Group name: ${obj.group}
<li repeat.for="player of obj.values">
player: ${player.name}
</li>
</ul>


Is it possible to do? Or what the better way to do this logic in Aurelia way?

Leo Leo
Answer

You can do this using a ValueConverter.

export class GroupByValueConverter {
    toView(array, groupBy) {

        var groups = {};

        array.forEach(function (o) {
            var group = o[groupBy];
            groups[group] = groups[group] || [];
            groups[group].push(o);
        });

        return Object.keys(groups).map(function (group) {
            return {
                group: group,
                values: groups[group]
            };
        })
    }
}