Pay attention at the moment you realize you have a comparable story. Because it is at that exact moment that you have stopped listening to the other person and are instead thinking about what you want to say: You are listening for your chance to jump in, and ignoring the other person.
So — STOP thinking about your own story and go back to listening to the other person. Maybe ask for some elaboration, or continuation, or clarification. Encourage them to tell their story, and let them. What are they telling you? What happened, what did they bring from it? Shut up and listen. Listening is a harder skill than talking. Develop it.
On telling a sympathetic story that comes across as one-upping
I post the above quote in my Facebook feed the other day. I've been keeping it in my back pocket for years and decided to finally get it out of my system. I just had to wait for enough time to pass so that no one in particular thinks I'm talking about them.
A lot of my friends do this and I'm sure a lot of your friends do too. I was taught to let someone else finish speaking before interrupting and I figure if I have something to say I can wait my turn. That doesn't mean I never interrupt or threadjack in RL or change the subject to the point where we cannot return to the original topic. Rather, I'm just a good listener and it is the exception more than the rule when I do it.
I had a short story to share that demonstrates this but I've delete it because the person it's about would benefit more from a hug and a good therapist (calling Dr X) instead of my calling them out anonymously on the internet.