Unless your omitting critical details just make this a condition of a Smart collection where the inventory stock is greater than 0
would you mind checking our app Nada - https://apps.shopify.com/nada-sort-hide-out-of-stock
The app is automatically sorting collections in real-time, so the sold-out products are always at the end of the collection and back when in stock again. You can try it for free to check that it really works smoothly.
Try it for free for 7 days and check if it helps to solve your problem.
Our app, Push Down & Hide Out of Stock, does exactly what you want!
It is pushing sold-out products to the bottom of collections or hiding them completely. Or you can combine both approaches and hide them after being sold out for few days. If a product is back in stock, it is unhid and moved to the original position automatically
It has an easy setup, and also it works instantly.
If you have any questions, please don't hesitate to reach out to us at firstname.lastname@example.org