I was trying to solve a Codewars Kata that requires a 47 bytes code solution for reversing an array of any[] type. The catch is – you cannot use .reverse()
. As a solution I came up with using .sort()
like this:
const reverse = (a: any[]) => a.sort(() => -1);
It works well, but I encountered a problem with undefined
. So an array like this [undefined, 0]
will be reversed as expected into [0, undefined]
, but if you try to reverse [0, undefined]
with this method it just returns the same array back.
const reverse = (a: any[]) => a.sort(() => -1);
console.log(reverse([undefined, 0]));
console.log(reverse([0, undefined]));
I don’t quite understand how it works behind the scene, after all I am not even comparing anything, just return -1 to reverse it. Any ideas about this behavior?