2 ms·
sort() on JavaScript arrays sorts alphabetically (unless you pass a compareFunction) https://stackoverflow.com/questions/21019902/why-cant-javascript-sort-5-10
by tosh 6y ago
sort() on JavaScript arrays sorts alphabetically (unless you pass a compareFunction)
https://stackoverflow.com/questions/21019902/why-cant-javascript-sort-5-10-1 https://stackoverflow.com/questions/21019902/why-cant-javasc...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- tobr 6y agoVery good point. I thought of it more as pseudocode.
- tosh 6y agoimho a very elegant solution and probably works in most languages, I was surprised by JavaScript's behaviour myself
- 1-more 6y agoFor a real fun headscratcher consider [ '9', '10', '11', '12', '13' ].map(parseInt)
- yboris 6y agoThank you for this exercise! I figured it out! [ROT 13] spoiler: cnefrVag frpbaq nethzrag vf onfr, znc frpbaq nethzrag vf vaqrk va neenl. 10 vf gur frpbaq nethzrag, vaqrk 1. cnefrVag(10, 1) unf vyyrtny onfr [0] https://rot13.com/ https://rot13.com/
- tgb 6y agoWait, really? I just had to double-check my one JS project for bugs and either I used to know this gotcha or I got lucky. My sort()-ing needed to handle NaNs carefully so I was already using custom comparators.
- yesbabyyes 6y agoGood point, for those who need to implement a slick compareFunction for numbers, Math.sign is great: [min, num, max].sort((a, b) => Math.sign(a - b))[1] An entirely different alternative is poor man's match: switch (true) { case num > max: return max; case num < min: return min; default: return num; }
- recursive 6y agoWhy sign though? I always write my sorts like this. .sort((a, b) => a - b)
- TimTheTinker 6y ago"lexicographically" is a better descriptor than "alphabetically", since it's sorting by UTF-8 code point value.
- edflsafoiewq 6y agoIt sorts by UTF-16 code unit.
- TimTheTinker 6y agoOf course, my bad.