For example, if you have the following [9, 8, 12, 1, 33, 21] array, using sort() on it will return [1, 12, 21, 33, 8, 9].
How UTF-16 Works
UTF-16 stands for 16-bit Unicode Transformation Format. It’s the standardized form for translating bits into a format comprehensible to humans. It’s basically a translation table for a corresponding character.
How to Turn Numbers Into Numbers ?
When sort() is used on its own, it returns values based on the order of things in the UTF-16 table. However, sort() also takes a callback function that allows you to decide how things will appear.
This callback function takes two arguments — a and b — for convention purposes. You use these arguments to create an equation that either returns 1, -1, or 0.
When the equation returns 1, a gets to proceed. If the equation returns -1, then b gets to proceed. If the equation equates to 0, then it means that both are equal in value and it is the end of the recursive sorting algorithm sort() runs through.
So when you’re working with numbers and using the callback function, the String() cast is not placed on the array items. This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback.
What About (a, b) => a- b ?
In many tutorials and StackOverflow answers, you may have seen solutions that look something like this: arrayNameHere.sort((a, b) => a - b);.
The thing with 1 and -1 is that it doesn’t have to be these two numbers specifically. It just needs to fall into one of the two spectrums of either being a positive or negative number. sort() will still treat it the same way as the code example above.
0 is a definite number that signifies the end of the sorting recursion, so this is the only non-negotiable value.
This is why (a, b) => a - b works. For example, if a = 5 and b = 2, a - b results in a positive number, making a the bigger number and returning the equivalent of 1.
It is good to note that this kind of sort logic only works with numeric types or objects that return numeric values when valueOf() is used.
Post a Comment