·
1 min read

JavaScript Tip: How to Sort an Array of Integers

MH

Michael Hoffmann

@mokkapps

JavaScript Tip: How to Sort an Array of Integers Image

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:

sort.js
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 BlueSky to get notified about new tips, blog posts, and more.