How to customize the grouping method

Grab this script and modify it to your needs: