Formation of ultra-diffuse galaxies in the field and in galaxy groups