Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to define custom sort function in JavaScript?
Creating custom sort functions in JavaScript allows you to control exactly how array elements are ordered. By defining a custom sort function, you can sort elements in specific ways that go beyond the default string-based sorting behavior.
This article will explain how to define custom sort functions in JavaScript, provide practical examples, and show different sorting techniques.
Understanding the Default sort() Behavior
By default, the sort() method converts elements to strings and compares them lexicographically. This can lead to unexpected results with numbers:
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<script>
let numbers = [10, 5, 40, 25, 1000, 1];
let defaultSort = numbers.slice().sort();
document.getElementById("demo1").innerHTML = "Default sort: " + defaultSort;
</script>
</body>
</html>
Default sort: 1,10,1000,25,40,5
Custom Sort Function Syntax
A custom sort function takes two parameters and returns:
- Negative value: First element comes before second
- Zero: Elements are equal
- Positive value: First element comes after second
array.sort(function(a, b) {
// Return negative, zero, or positive number
return comparison_result;
});
Example: Sorting Numbers Numerically
<!DOCTYPE html>
<html>
<body>
<p id="demo2"></p>
<script>
let numbers = [10, 5, 40, 25, 1000, 1];
// Ascending order
let ascending = numbers.slice().sort(function(a, b) {
return a - b;
});
// Descending order
let descending = numbers.slice().sort(function(a, b) {
return b - a;
});
document.getElementById("demo2").innerHTML =
"Ascending: " + ascending + "<br>" +
"Descending: " + descending;
</script>
</body>
</html>
Ascending: 1,5,10,25,40,1000 Descending: 1000,40,25,10,5,1
Example: Sorting Strings Alphabetically
<!DOCTYPE html>
<html>
<body>
<p id="demo3"></p>
<script>
let cars = ['BMW', 'BENZ', 'AUDI', 'DUCATI'];
cars.sort(function(x, y) {
if (x < y) return -1;
if (x > y) return 1;
return 0;
});
document.getElementById("demo3").innerHTML = "Sorted cars: " + cars;
</script>
</body>
</html>
Sorted cars: AUDI,BENZ,BMW,DUCATI
Example: Sorting Objects by Property
<!DOCTYPE html>
<html>
<body>
<p id="demo4"></p>
<script>
function sortBy(field) {
return function(a, b) {
return (a[field] > b[field]) - (a[field] < b[field]);
};
}
let cars = [
{id: 23, car: 'wagnor'},
{id: 40, car: 'dzire'},
{id: 14, car: 'swift'}
];
cars.sort(sortBy('car'));
document.getElementById("demo4").innerHTML = JSON.stringify(cars);
</script>
</body>
</html>
[{"id":40,"car":"dzire"},{"id":14,"car":"swift"},{"id":23,"car":"wagnor"}]
Example: Custom Order Sorting
<!DOCTYPE html>
<html>
<body>
<p id="demo5"></p>
<script>
let customOrder = ['tilak', 'bheem', 'avathar'];
let people = [
{name: 'avathar'},
{name: 'tilak'},
{name: 'bheem'},
{name: 'tilak'}
];
people.sort(function(a, b) {
return customOrder.indexOf(a.name) - customOrder.indexOf(b.name);
});
document.getElementById("demo5").innerHTML = JSON.stringify(people);
</script>
</body>
</html>
[{"name":"tilak"},{"name":"tilak"},{"name":"bheem"},{"name":"avathar"}]
Common Sorting Patterns
| Sort Type | Compare Function | Use Case |
|---|---|---|
| Numbers Ascending | (a, b) => a - b |
Numerical sorting |
| Numbers Descending | (a, b) => b - a |
Reverse numerical |
| Strings Ascending | (a, b) => a.localeCompare(b) |
Alphabetical sorting |
| Custom Order | indexOf comparison |
Priority-based sorting |
Conclusion
Custom sort functions give you complete control over array ordering. Use numeric comparison for numbers, localeCompare() for strings, and property-based comparisons for objects to achieve the exact sorting behavior you need.
