Skip to content

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
sort()

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

// Compare function
sort(compareFn)

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

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

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

JavaScript Sort Compare Function

Simple example code where the 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>
<html>
<body>
  <script>
   const num = [9, 10, 1, 5, 2, 10];
   num.sort(function(a, b){return a - b});

   console.log(num);
 </script>
</body>
</html> 

Output:

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.

strings

var animals = ["Horse", "Cat", "Tiger", "Lion"];  
animals.sort();

numbers

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

Sorting numbers in ascending order:

const numbers = [5, 2, 9, 1, 5];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); // [1, 2, 5, 5, 9]

Sorting strings in alphabetical order:

const fruits = ["apple", "banana", "cherry", "date"];
fruits.sort(function(a, b) {
  return a.localeCompare(b);
});
console.log(fruits); // ["apple", "banana", "cherry", "date"]

Custom sorting order:

const colors = ["green", "red", "blue", "yellow"];
const customOrder = ["red", "green", "blue", "yellow"];
colors.sort(function(a, b) {
  return customOrder.indexOf(a) - customOrder.indexOf(b);
});
console.log(colors); // ["red", "green", "blue", "yellow"]

Sorting objects based on a property:

const students = [
  { name: "Alice", age: 22 },
  { name: "Bob", age: 18 },
  { name: "Charlie", age: 25 }
];
students.sort(function(a, b) {
  return a.age - b.age;
});
console.log(students);
// [{ name: "Bob", age: 18 }, { name: "Alice", age: 22 }, { name: "Charlie", age: 25 }]

In each example, the compareFunction defines the sorting criteria based on the specific requirements. You can adapt and customize the compare function to suit your sorting needs.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading