Recently, I encountered a situation where I had to add grouping in Views based on a condition. The scenario was - I had an exposed sorting dropdown which had three options viz. Date(Asc), Date(Desc) & Category. Now when a user will sort the Views using Category then the Views should be grouped by the category names.
Drupal has 4 View hooks which acts on the Views before it is being displayed and I was a bit unsure about using
First, I added the group in my View through Views UI and exported the configuration using Drupal 8
With all these gatherings and a couple of hours of hit and trials finally I had a working code which grouped the View items by category when sorted by Category field.