Filtering Repeating Group

I have a chat functionality that receives data from a datatype called CHAT. Everytime a message is sent, a new chat is created.

The challenge is, when retrieving these chats a Repeating group before a user can click on a specific chat to open up the messages in that chat, all the chats comes up as single entries in the Repeating group.

What I want is to have all the chats between two users to come as a single chat.

Any help with that?