Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Custom Array Sort Algorithms in JavaScript
JavaScript Joel
JavaScript Joel

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 ]
Enter fullscreen modeExit fullscreen mode

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}]
Enter fullscreen modeExit fullscreen mode

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}
Enter fullscreen modeExit fullscreen mode

Then pass that function to thesort method.

myArray.sort(compareFunction)
Enter fullscreen modeExit fullscreen mode

This flexibility will allow us to be creative with our sorting algorithms.

Number Sort

To sort aNumberArray 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 ]
Enter fullscreen modeExit fullscreen mode

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']},]
Enter fullscreen modeExit fullscreen mode

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' ] } * ] */
Enter fullscreen modeExit fullscreen mode

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"]
Enter fullscreen modeExit fullscreen mode

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' ]
Enter fullscreen modeExit fullscreen mode

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.

Cheers 🍻

Photo byKelly Sikkema onUnsplash

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
  • Joined

More fromJavaScript Joel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp