Skip to content

Commit 4312073

Browse files
committed
Create a mapToGroups method
1 parent 6de58f5 commit 4312073

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/Illuminate/Support/Collection.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,25 @@ public function map(callable $callback)
704704
return new static(array_combine($keys, $items));
705705
}
706706

707+
/**
708+
* Run a grouping map over the items.
709+
*
710+
* The callback should return an associative array with a single key/value pair.
711+
*
712+
* @param callable $callback
713+
* @return static
714+
*/
715+
public function mapToGroups(callable $callback)
716+
{
717+
$groups = $this->map($callback)->reduce(function ($groups, $pair) {
718+
$groups[key($pair)][] = reset($pair);
719+
720+
return $groups;
721+
}, []);
722+
723+
return (new static($groups))->map([$this, 'make']);
724+
}
725+
707726
/**
708727
* Run an associative map over each of the items.
709728
*

tests/Support/SupportCollectionTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,24 @@ public function testFlatMap()
10491049
$this->assertEquals(['programming', 'basketball', 'music', 'powerlifting'], $data->all());
10501050
}
10511051

1052+
public function testMapToGroups()
1053+
{
1054+
$data = new Collection([
1055+
['id' => 1, 'name' => 'A'],
1056+
['id' => 2, 'name' => 'B'],
1057+
['id' => 3, 'name' => 'C'],
1058+
['id' => 4, 'name' => 'B'],
1059+
]);
1060+
1061+
$groups = $data->mapToGroups(function ($item, $key) {
1062+
return [$item['name'] => $item['id']];
1063+
});
1064+
1065+
$this->assertEquals(['A' => [1], 'B' => [2, 4], 'C' => [3]], $groups->toArray());
1066+
$this->assertInstanceOf(Collection::class, $groups);
1067+
$this->assertInstanceOf(Collection::class, $groups['A']);
1068+
}
1069+
10521070
public function testMapWithKeys()
10531071
{
10541072
$data = new Collection([

0 commit comments

Comments
 (0)