Factory resetting a device will clean up all the data on the device including malware. However, it might not work in certain cases like a rootkit.