Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,25 @@ public function map(callable $callback)
return new static(array_combine($keys, $items));
}

/**
* Run a grouping map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @return static
*/
public function mapToGroups(callable $callback)
{
$groups = $this->map($callback)->reduce(function ($groups, $pair) {
$groups[key($pair)][] = reset($pair);

return $groups;
}, []);

return (new static($groups))->map([$this, 'make']);
}

/**
* Run an associative map over each of the items.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,35 @@ public function testFlatMap()
$this->assertEquals(['programming', 'basketball', 'music', 'powerlifting'], $data->all());
}

public function testMapToGroups()
{
$data = new Collection([
['id' => 1, 'name' => 'A'],
['id' => 2, 'name' => 'B'],
['id' => 3, 'name' => 'C'],
['id' => 4, 'name' => 'B'],
]);

$groups = $data->mapToGroups(function ($item, $key) {
return [$item['name'] => $item['id']];
});

$this->assertInstanceOf(Collection::class, $groups);
$this->assertEquals(['A' => [1], 'B' => [2, 4], 'C' => [3]], $groups->toArray());
$this->assertInstanceOf(Collection::class, $groups['A']);
}

public function testMapToGroupsWithNumericKeys()
{
$data = new Collection([1, 2, 3, 2, 1]);

$groups = $data->mapToGroups(function ($item, $key) {
return [$item => $key];
});

$this->assertEquals([1 => [0, 4], 2 => [1, 3], 3 => [2]], $groups->toArray());
}

public function testMapWithKeys()
{
$data = new Collection([
Expand Down