JavaScript Tip: How to Sort an Array of Integers
In JavaScript, Array.prototype.sort()
sorts the elements of an array in place and returns the reference to the same array, now sorted.
The default sort order is ascending, built upon converting the elements into strings and comparing their UTF-16 code unit value sequences.
sort()
mutates the original array. Therefore we use [...numbers]
to create a shallow copy of the array in the following example.
To sort an array of integers, we must provide a compare function that defines the sort order:
If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.
JavaScript Tip: Throw an Error if a Required Parameter Is Missing
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed. We can use this approach to write a function that throws an error if a required parameter is missing.
JavaScript Tip: Get Valuable Info About Device Battery
TODO