1
first
2
second
This is a job for Muenchian Grouping. You will numerous examples of it within the XSLT tag here on StackOverflow.
First, you need to define a key to help you group the groups
This will look up group elements for a given group name.
Next, you need to match all the occurrences of the first instance of each distince group name. This is done with this scary looking statement
i.e Match group elements which happen to be the first occurence of that element in our key.
When you have matched the distinct group nodes, you can then loop through all other group nodes with the same name (where $currentGroup is a variable holding the current group name)
Putting this altogether gives
Applying this on your sample XML gives the following result
1
first
3
first
2
seccond