The default ECMAScript sort is alphabetical, so a little magic is needed to sort an array in numerical order.
Photo by Sora Sagano on Unsplash
Ever try to sort an array of integers in JavaScript using .sort() and get a weird result, where the order was not numeric?
What is going on here?
The array got sorted in lexicographical order (that is, alphabetically), so each integer actually got coerced into a string type.
Then each string was compared, which is why -10 came before -14 and 23 came before 3 ? strings are compared character-by-character.
The solution to achieve a numeric sort is passing a comparison function to the .sort() method as a parameter.
Photo by Elliot Banks on Unsplash
Use .sort((a,b) => a-b)
In order to sort a list in numerical order, the Array.prototype.sort() method needs to be passed a comparison function.
To sort the array numerically in ascending order, That comparison function should return the difference between the two numbers.
This is achieved by subtracting the second item from the first.
That?s more like it!
The (a,b)=>a-b comparison function subtracts the second item from the first item, thus returning a negative value if the second item is bigger, a positive value if the second item is smaller, and 0 for equality.
Photo by Mark Tegethoff on Unsplash
Descending numerical sort
A descending sort would just need the operators reversed, so the comparison function becomes (a,b)=>b-a:
Photo by Anthony DELANOIX on Unsplash
Protecting the original with .sort()
In addition to returning the sorted array, the .sort() method sorts the array in-place, changing the value stored for that variable.
Since arrays are objects in JavaScript, their contents can still be changed even if they are created using the const keyword.
So, there needs to be a way to keep the original array intact and prevent it from being changed. One way is using Array.prototype.slice():
Other options are using the spread operator (?) or Object.assign() :
Photo by Shawnn Tan on Unsplash
Conclusion
Sorting an array in JavaScript is actually pretty powerful because of how comparison functions work: -1 for <, 0, and 1 for >.
That being said, it is pretty confusing that the default sort is always alphabetical? even when the array has numbers in it, not strings.
We can use .sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or .sort((a,b)=>b-a) for descending order.
The .sort() method sorts the array in-place, so if necessary we can make a copy while sorting by using the syntax [?array].sort() .
Get out there and sort some arrays! You can do it!
Photo by Daniel Hehn on Unsplash
Further reading
- Alligator.io published an article about sorting arrays of numbers:
Using JavaScript’s sort Method for Sorting Arrays of Numbers
The sort method available on the Array prototype allows you to sort the elements of an array and control how the?
alligator.io
- RadDevon.com also has an article about sorting arrays of numbers:
How do I sort an array of numbers in Javascript?
Let’s say you have a Javascript array of numbers like this: let numbers = [85, 83, 29, 70, 4, 0, 17, 8, 55]; You want?
raddevon.com
- Krunal Lathiya wrote about array sorting at his blog AppDividend:
Javascript Array Sort Example | Array.prototype.sort() Tutorial
Javascript Array Sort Example | Array.prototype.sort() Tutorial is today’s leading topic. The sort() method sorts all?
appdividend.com
- Banesa Guaderrama explains how to sort arrays of strings on Dev.to:
Sorting Arrays of Strings in JavaScript
In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The following?
dev.to
- Phil Nash wrote a tongue-in-cheek article ?How not to sort an array?:
How not to sort an array in JavaScript
Array sorting is one of those things you don’t spend too long thinking about, until it stops working for you. Recently?
philna.sh
Photo by Banter Snaps on Unsplash