Re:JavaScript for Microcontrollers
by fallenatreus on Monday November 23, 2020 @07:10PM
(#25193585)
Well, not if you know that .sort(); is meant to accept a custom sort function too [1,2,10,20].sort((a,b)=>b-a)) // 1, 2, 10, 20
[ Parent
| on HN ]
Re:JavaScript for Microcontrollers
by frankenst1 on Tuesday November 24, 2020 @05:59AM
(#25197325)
The issue here is that for some reason I often struggle to remember which function sorts in ascending order [(b-a) or (a-b)].
In fact, your example suffers from the same problem: It sorts in descending order (20,10,2,1) instead of ascending (1,2,10,20).
Telling JS to use a TypedArray [Int8,...,BigInt64] instead can solve this without remembering and providing your own comparator:
Float64Array.from([1,2,10,20]).sort(); //[1,2,10,20]