The bug
The problem is the order in which worlds register matching entities. Currently, the order will always be: nether, end, overworld. When commands are executed from the overworld or the end, and the "limit" argument is used (while sorted by distance), the first matched entities will always be from the nether. This created some inconsistencies like the one described in this bug report (I can't find a concise and good title).
The fix is not that hard since there is already a method that return the list of affected dimension. This list must be reorganized to put the current dimension first.
How to reproduce
- Go to coordinates 0 10 0 in the overworld and place an armor stand
/summon armor_stand 0 10 0 {NoGravity:1b,CustomName:"[\"overworld\"]"}
- Go to the nether to coordinates 0 10 0 and place an armor stand and forceload the chunk
/summon armor_stand 0 10 0 {NoGravity:1b,CustomName:"[\"nether\"]"} /forceload add 0 0
- Return to the overworld and run the following command
/say @e[type=armor_stand,limit=1,sort=nearest]
→ It says the name of the armor stand in the nether