Hello All,
Why are these two codes giving different outputs when using the comparator function? Is it based on the unicode value of the first letters(‘N’ and ‘J’)or the length of the string(amount of characters)?
The explanation of the first link is clear, and about the ascii table : the decimal number of each character is different so if you’re getting different result it’s because of the decimal number and the condition you have set in your code.
Hi thank you for the attachments. But I still need clarification on the how/why the second code is executed.
I understand Mosh’s method and how comparator function is applied, and that the result is ascending(least => greatest); based on the ASCII Table you linked ‘N’ = 78 and ‘J’ = 74 so:
function(a,b){ return 78 - 74}
// 78 - 74 = 4(positive value) so a>b returns 1 meaning b comes ahead of a
However, the second code should give the same result,
Yes you’re right, i tried everything with your code but nothing worked.
But i think the reason your code isn’t working is because sorting strings is different from numbers, and as document mentioned :
To compare numbers instead of strings, the compare function can simply subtract b from a
Thank you for taking the time, that makes more sense. I simply thought I could try the shorter syntax, since it was cleaner, but I believe you are right: sorting value vs. string are different. The Mosh tutorial video only showed sort by string, so i assumed this applies to numbers by default.
The second method doesn’t work because subtracting a string from another doesn’t give a sensible numeric result. How much is “Node.js” minus “Javascript”? It’s NaN .