If one is only interested to remove duplicates (your script does more) I've found this one liner in a StackExchange post:
awk '!x[$0]++' ~/.zsh_history
Note that this only keeps the first copy, not the most recent copy. To make it so that it only keeps the most recent, you would need to run this through `tac` twice.