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
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.
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
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
- Alligator.io published an article about 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?
- RadDevon.com also has an article about sorting arrays of numbers:
- Krunal Lathiya wrote about array sorting at his blog AppDividend:
- Banesa Guaderrama explains how to sort arrays of strings on Dev.to:
- Phil Nash wrote a tongue-in-cheek article ?How not to sort an array?:
Array sorting is one of those things you don’t spend too long thinking about, until it stops working for you. Recently?
Photo by Banter Snaps on Unsplash