Hi Shikha,
Grouping of components should not be driven dynamic. You need to mentioned the component group when you create the components and group the components logically based on a criteria may be feature wise, site wise etc..
Now, once you have the component groups and the components in the group, then you can control what components needs to be displayed/enable on a page/template. So when author creates a page, then all the components for that template would be displayed.
Also, before customizing all of that programmatically, we will have to think why this approach doesnt work and also is it worth customizing so much !
Please give us your use case aswell so that we can see if there is any better approach for the same.
Thanks,
Lokesh