Search code examples
laravellaravel-collection

Distinct and sort collection based on duplicate count


I have the following collection

$collection = collect([
    ['id' => 1, 'name' => 'Design'],
    ['id' => 2, 'name' => 'Art'],
    ['id' => 3, 'name' => 'Comms'],
    ['id' => 2, 'name' => 'Art'],
    ['id' => 3, 'name' => 'Comms'],
    ['id' => 3, 'name' => 'Comms'],
]);

I want only unique items in the collection and the collection should be sorted by number of duplicates. So an item which has most number of duplicates must appear on top as follows

$collection = collect([
        ['id' => 3, 'name' => 'Comms'],
        ['id' => 2, 'name' => 'Art'],
        ['id' => 1, 'name' => 'Design'],
    ]);

I can remove duplicates using unique method but cannot find a want to sort them.


Solution

  • You can do it with mapWithKeys()

    https://laravel.com/docs/8.x/collections#method-mapwithkeys

    $collection = $collection->groupBy('id')->mapWithKeys(function (Collection $row) {
        return [$row->count() => $row->first()];
    })->sortKeysDesc();