The easiest way to do this is to download the latest installer for Sonoma.
Use that to create an installer USB. A USB thumb drive will work just fine for that.
Apple has OK steps for doing that from
your Terminal app.
Boot your iMac from that USB installer, and follow the steps to install Sonoma