Sounds related to the bin packing problem.
Maybe this JavaScript library would be helpful inspiration: