JavaScript Sort Compare Function | Example code

  • by

When you call the sort() method, with a custom compare function, the compare function is called on pairs in your to-be-sorted list, to determine the proper ordering in JavaScript.

// Functionless

// Arrow function
sort((a, b) => { /* ... */ } )

// Compare function

// Inline compare function
sort(function compareFn(a, b) { /* ... */ })

Note: the sort() method will give the right sorted array when sorting numbers. Using compare function can fix it.

function compare(a,b) {
    return a - b;

JavaScript Sort Compare Function

Simple example code where compare function must take two arguments often referred to as a and b. Then you make the compare function return 0, greater than 0, or less than 0, based on these values, a and b.

<!DOCTYPE html>
   const num = [9, 10, 1, 5, 2, 10];
   num.sort(function(a, b){return a - b});



JavaScript Sort Compare Function

More examples

Sort method alone treat numbers as strings so if the array of strings you don’t need the compare function. but if the array of numbers you need the compare function to alter the build behavior of the sort method.


var animals = ["Horse", "Cat", "Tiger", "Lion"];  


var marks = [70, 90, 60, 80 ];  
marks.sort(function(a, b){return a > b}); //ascending , a < b descending . 
compareFunction(a, b) return valuesort order
> 0sort b before a
< 0sort a before b
=== 0keep original order of a and b

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

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