Problems with filterBy

sorry for the dumb question, but I can’t figure this out. I’ve looked at other similar problems, but I wasn’t able to piece things together there either.
I have a number of pages which I would like to list by fields lastname and firstname. I’m able to get all the names listed and sorted, but I am unable to omit the duplicates.
I have tried filterBy, but it doesn’t work.
$artists = $site->page('categories')->grandChildren()->invisible()->sortBy('lastname','asc'); <?php foreach ($artists as $artist): ?> <?php echo $artist->lastname() . ', ' . $artist->firstname() ?> <?php endforeach ?>

Don’t know if this is the most effective way of doing it, but you could use groupBy()

<?php
  $groupedArtists = $page->children()->visible()->sortBy('lastname', 'asc')->group(function($p){
    return $p->lastname() . '-' . $p->firstname();
  });

  foreach ($groupedArtists as $name => $artists):
    $count = 0;
    foreach($artists as $artist):
      if($count == 0) { echo $artist->lastname() . ', ' . $artist->firstname(); } 
      $count++;
    endforeach;
  endforeach;
?>
1 Like

It works for me! Thanks so much for your help. I’ve never used the groupBy function. so yet again I learn something new from the forum!

You could use the map() method to generate a new collection with fullnames and pluck() to get an array of unique names.

$artists = $site->page('categories')
                ->grandChildren()
                ->invisible()
                ->sortBy('lastname','asc')
                ->map(function($artist) {
                    return [ 'fullName' => $artist->lastname() . ', ' . $artist->firstname() ];
                })->pluck('fullName', null, true);

<?php foreach ($artists as $artistFullName): ?>
<?php echo $artistFullName ?>
<?php endforeach ?>
2 Likes

@pedroborges: pretty cool :slight_smile:

Awesome! Thanks! I tried it out and it works too