Reorder a list of percentage width flex items so that each row adds up to 100%

I’m hoping someone might be able to point me in the right direction. I’ve got a fairly simple grid of flex items where the height is set to auto but they have varying widths 33%, 50%, 67%, 100% and wrap to the next row.

This is all good when the items are in the right order. But what I’m trying to achieve is a way to shuffle the items into an order which fits when they’re added to the page randomly.

Example, a list of items 50 | 33 | 67 | 50 | 100 might be reordered to 50 | 50 | 67 | 33 | 100 so each row uses up the most horizontal space it can. I might have a list of 100 or so items, and it would also be nice to mix them up a bit and not have say 10 50% width items all together, but some rows of 33 | 33 | 33 or 33 | 67 mixed in between them.

I can’t think of a way to do this using CSS alone. So I’ve been looking at various JavaScript libraries, but they all seem to be focused on shuffling items of varying height and a fixed width.

I don’t need to change the display or position of the items, just the order based on their widths, so maybe I’m overthinking it and something like putting them into an array and sorting that would work better.

Any help would be much appreciated! 🙂