JavaScript Array.sort with examples

I was reading a social post and found that Array.sort() works great across all the browser. I thought to write small demo to show powerful compare function to sort object type array on given property.

Example: Array.sort()

Also, Array.sort() is a string sort by default! Should be used for string like type only!

array-sort array-sort-output

So, you can not use for Array.sort() for numeric sort! 🙁

But, you can use compare callback function to work with Object type Array very efficiently.

Example: Array.sort(compareFunction)

array-sort-compare-function array-sort-compare-function-output

Read: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort?redirect=no

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.