
Posted on • Originally published atjoel.net
Custom Array Sort Algorithms in JavaScript
JavaScript's Default Array Sort
JavaScript'sArray.sort
defaults to aString
sort. This catches many people off guard when attempting to sort anArray
of typeNumber
.
// ❌ Default search is a String searchconstnumbers=[10,1,3,15]numbers.sort()// [ 1, 10, 15, 3 ]
In the above example, eachNumber
is converted to aString
and then sorted using aString
sort.
At first, this can seem like a WTF JavaScript moment, but this happens because anArray
can contain mixed elements and JavaScript doesn't know how it should sort. Sosort
defaults to aString
sort.
constarray=[1,2,3,'Joel',4,{userId:123}]
When we want something other than aString
sort, we have to be explicit.
Custom Sort Compare Function
Creating a custom sort compare function is pretty easy. The function takes two elements, then we return-1
if the first is lower and1
if it's higher.0
for the same.
constcompareFunction=(a,b)=>{// Pseudo Codeif(aislessthanb)return-1if(aismorethanb)return1return0}
Then pass that function to thesort
method.
myArray.sort(compareFunction)
This flexibility will allow us to be creative with our sorting algorithms.
Number Sort
To sort aNumber
Array
we could create a customcompareNumbers
function and pass that intoArray.sort
.
constcompareNumbers=(a,b)=>a-bconstnumbers=[10,1,3,15]numbers.sort(compareNumbers)// [ 1, 3, 10, 15 ]
Custom Object Sort
Let's say we had some data that looks like this:
constcustomers=[{id:1,orders:['a-1000','x-2000','c-8000']},{id:2,orders:['a-1010']},{id:3,orders:['a-1040','c-8050']},]
Our requirement is to sort by the number (length
) oforders
. So the order should be2
,3
,1
.
We can do that with a customcompareOrderLength
function that will sort bycustomer.orders.length
.
constcompareOrderLength=(a,b)=>a.orders.length-b.orders.lengthcustomers.sort(compareOrderLength)/** * [ * { id: 2, orders: [ 'a-1010' ] }, * { id: 3, orders: [ 'a-1040', 'c-8050' ] }, * { id: 1, orders: [ 'a-1000', 'x-2000', 'c-8000' ] } * ] */
Complex Custom Sorting
I recently had a use case where an API was returning data that looked like this.
// API Response["1","10","2","BLA","BLA2","3"]
TheArray
contained allString
items, but the business wanted the items to display like "1, 2, 3, 10, BLA, BLA2".
That meant, I had to detect when theString
was aNumber
and Sort the "numbers" first and the text after.
As complex as that sounds, the sort algorithm wasn't too bad.
constisNumeric=(num)=>!isNaN(num)constcustomCompare=(a,b)=>{if(isNumeric(a)&&!isNumeric(b))return-1if(!isNumeric(a)&&isNumeric(b))return1if(isNumeric(a)&&isNumeric(b))returna-breturna<b?-1:1}// [ '1', '2', '3', '10', 'BLA', 'BLA2' ]
End
So just remember the defaultArray
sort is aString
sort. To sort by anything else, you must create a compare function and pass that into sort.
- Check out my 📰Newsletter
- Subscribe to my 📺 YouTube,JoelCodes
- Say hi to me on Twitter@joelnet
Cheers 🍻
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse