Skip to content

[5.8] Add countBy method to Collection - #27770

Merged
taylorotwell merged 3 commits into
laravel:5.8from
jamierumbelow:add_collection_tally
Mar 5, 2019
Merged

taylorotwell merged 3 commits into
laravel:5.8from
jamierumbelow:add_collection_tally

Conversation

@jamierumbelow

@jamierumbelow jamierumbelow commented Mar 4, 2019 •

Copy link
Copy Markdown
Contributor

Adds a countBy method to Illuminate\Support\Collection.

By default, this method counts each appearance of a given value:

collect([ 1, 2, 2, 2, 3 ])->countBy(); // == collect([ 1 => 1, 2 => 3, 3 => 1 ])

It also accepts a predicate:

collect([ 1, 2, 2, 3, 4 ])->countBy(function ($i) {
    return $i % 2 === 0;
}); // == collect([ true => 3, false => 2 ])

collect([ 'alice@gmail.com', 'bob@yahoo.fr', 'carlos@gmail.com' ])
    ->countBy(function ($email) {
        return substr(strrchr($email, "@"), 1);
    }); // == collect([ 'gmail.com' => 2, 'yahoo.fr' => 1 ])

@driesvints driesvints changed the title Add countBy method to Collection [5.8] Add countBy method to Collection Mar 4, 2019

@driesvints driesvints left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please fix the StyleCI warnings.

Comment thread src/Illuminate/Support/Collection.php Outdated
public function countBy($predicate = null)
{
if (is_null($predicate)) {
$predicate = function ($val, $key) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$predicate = function ($val, $key) {
$predicate = function ($val) {

You aren't utilizing the $key so it doesn't need to be set.

@driesvints
driesvints dismissed their stale review March 5, 2019 10:52

StyleCI warnings fixed.

@taylorotwell
taylorotwell merged commit 563af72 into laravel:5.8 Mar 5, 2019
@jamierumbelow
jamierumbelow deleted the add_collection_tally branch March 5, 2019 13:39
@vlakoff

vlakoff commented Mar 11, 2019 •

Copy link
Copy Markdown
Contributor

For the "without predicate" mode, couldn't we use array_count_values()? Probably much, much faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants