Skip to content

Commit d1ea2e2

Browse files
JosephSilbertaylorotwell
authored andcommitted
Create a mapToGroups method (#18949)
1 parent fdb464a commit d1ea2e2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Illuminate/Support/Collection.php

+19
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

+29
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,35 @@ 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->assertInstanceOf(Collection::class, $groups);
1066+
$this->assertEquals(['A' => [1], 'B' => [2, 4], 'C' => [3]], $groups->toArray());
1067+
$this->assertInstanceOf(Collection::class, $groups['A']);
1068+
}
1069+
1070+
public function testMapToGroupsWithNumericKeys()
1071+
{
1072+
$data = new Collection([1, 2, 3, 2, 1]);
1073+
1074+
$groups = $data->mapToGroups(function ($item, $key) {
1075+
return [$item => $key];
1076+
});
1077+
1078+
$this->assertEquals([1 => [0, 4], 2 => [1, 3], 3 => [2]], $groups->toArray());
1079+
}
1080+
10521081
public function testMapWithKeys()
10531082
{
10541083
$data = new Collection([

0 commit comments

Comments
 (0)