Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] Create a mapToGroups method #18949

Merged
merged 1 commit into from
Apr 27, 2017
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