You'd probably need to reduce it to a hash of name to total and then map
that back to a Mojo::Collection, e.g.:
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::Collection;
use Data::Dumper;
my $collection= Mojo::Collection->new({name=>"name1", total=>2},
{name=>"name1",total=>3}, {name=>"name2", total=>7});
my $firstPass = $collection->reduce( sub {
$a->{$b->{name}} += $b->{total};
return $a;
}, {});
my $newCollection = Mojo::Collection->new(
map {
{ name => $_, total => $firstPass->{$_} }
} keys %{$firstPass}
);
print Dumper($collection);
print Dumper($newCollection);
On Friday, 3 August 2018 13:50:19 UTC+1, Stefan Adams wrote:
>
> I have a Mojo::Collection of hashes and I'd like to reduce the collection
> similar to an SQL GROUP BY.
>
> Mojo::Collection->new({name=>"name1", total=>2}, {name=>"name1",total=>3},
> {name=>"name2", total=>7})
>
>
> This collection has three elements and the collection I'm looking for
> would have two:
>
> {name=>"name1", total=>*5*}, {name=>"name2",total=>7}
>
>
> I'm trying to group by name and then sum the totals within that group.
>
> It seems like I should use the reduce method of Mojo::Collection; if
> that's appropriate, how could I accomplish that?
>
--
You received this message because you are subscribed to the Google Groups
"Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.