JavaScript Tip: How to Sort an Array of Integers

Michael Hoffmann
Jan 2, 2023
| 1 min read
| 22 views
Michael Hoffmann
Jan 2, 2023
1 min read
| 22 views
Javascript

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:
const numbers = [10, 3, 45, 999, 20]const ascendingSortedNumbers = [...numbers].sort((a, b) => a - b)console.log(ascendingSortedNumbers) // [ 3, 10, 20, 45, 999 ]const descendingSortedNumbers = [...numbers].sort((a, b) => b - a)console.log(descendingSortedNumbers) // [ 999, 45, 20, 10, 3 ]
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 MissingDec 26, 2022
JavaScript Tip: Get Valuable Info About Device BatteryJan 9, 2023
Show comments