2 added 42 characters in body
source | link

Edit: now including Michael E2's improvement.

Building on your own code and the existing answers this seems both cleaner and faster:

wizKP[x_List, n_] := Nearest[x -> Range @ Length @ xAutomatic, x, n]

Building on your own code and the existing answers this seems both cleaner and faster:

wizKP[x_List, n_] := Nearest[x -> Range @ Length @ x, x, n]

Edit: now including Michael E2's improvement.

Building on your own code and the existing answers this seems both cleaner and faster:

wizKP[x_List, n_] := Nearest[x -> Automatic, x, n]
1
source | link

Building on your own code and the existing answers this seems both cleaner and faster:

wizKP[x_List, n_] := Nearest[x -> Range @ Length @ x, x, n]