I've done a few different Liquid only sorting posts here before so let's run over another. This one will cover sorting products based on the stock count of product (and variants within).
Usual rules for custom sorting applies: your collection needs to have 50 or less items so we can sort them all on the one page without pagination. If you want to handle more than 50 items that's possible with JavaScript, but we're only looking at Liquid only methods here today.
Demo time
A demo is setup on the experiments store, on a specific collection.
Liquid Code
The code is very similar to an earlier one put together for sorting by metafield value. For the quick version I'll include the Liquid file before. For more detailed info jump to the github repo.
grabbing the code...