How to Sort an Array in JavaScript
Sorting numbers, strings and objects with the sort method.
When you need to put a list in order, like products by price or users by name,
JavaScript arrays have a built-in sort method. It has a gotcha that trips up
almost everyone the first time.
The sort() method sorts the items of an array in place and returns the
sorted array.
The Default Sort Gotcha
Without any arguments, sort converts every item to a string and compares them
alphabetically. That works for words but not for numbers:
const numbers = [10, 1, 5, 100, 2]numbers.sort()console.log(numbers) // [1, 10, 100, 2, 5]
As strings, "100" comes before "2" because "1" comes before "2". To sort
numbers correctly you need a compare function.
Using a Compare Function
The compare function gets two items, a and b, and returns a number:
- a negative number puts
abeforeb - a positive number puts
bbeforea 0leaves them where they are
For numbers, subtracting one from the other does exactly that:
const numbers = [10, 1, 5, 100, 2]numbers.sort((a, b) => a - b) // [1, 2, 5, 10, 100]numbers.sort((a, b) => b - a) // [100, 10, 5, 2, 1]
a - b sorts from lowest to highest and b - a sorts from highest to lowest.
Sorting Strings
The default sort works for simple words, but it puts every uppercase letter
before every lowercase one. localeCompare compares strings the way a person
would expect:
const names = ["pam", "Jim", "dwight", "Angela"]names.sort() // ["Angela", "Jim", "dwight", "pam"]names.sort((a, b) => a.localeCompare(b)) // ["Angela", "dwight", "Jim", "pam"]
Sorting an Array of Objects
Most of the time you'll be sorting objects by one of their properties. Compare that property inside the function:
const products = [{ name: "Monitor", price: 300 },{ name: "Keyboard", price: 80 },{ name: "Mouse", price: 40 },]products.sort((a, b) => a.price - b.price)// Mouse, Keyboard, Monitorproducts.sort((a, b) => a.name.localeCompare(b.name))// Keyboard, Monitor, Mouse
Since Chrome 70 and Node 11, sort is stable in Chrome, Firefox and Safari, and
the upcoming ES2019 spec makes it a requirement. That means items that compare
as equal keep their original order, so you can sort by name and then by price
and the names stay in order within each price.
sort Changes the Original Array
Unlike map or filter, sort changes the array you call it on. This can
cause bugs when the array is used somewhere else, like state in a React
component:
const scores = [3, 1, 2]const sorted = scores.sort((a, b) => a - b)console.log(scores) // [1, 2, 3], the original changed too
To keep the original, copy it first with the spread operator:
const scores = [3, 1, 2]const sorted = [...scores].sort((a, b) => a - b)console.log(scores) // [3, 1, 2]console.log(sorted) // [1, 2, 3]
Just remember to pass a compare function, and to copy the array before sorting it.
Have some feedback on this post? .