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 sort an array of integers correctly in JavaScript?
To sort an array of integers correctly in JavaScript, use the sort() method with a comparison function. Without a comparison function, sort() converts numbers to strings, causing incorrect ordering.
The Problem with Default sort()
JavaScript's default sort() method converts elements to strings and sorts alphabetically, which doesn't work correctly for numbers:
var numbers = [10, 2, 100, 5];
console.log("Default sort:", numbers.sort());
Default sort: [ 10, 100, 2, 5 ]
Correct Integer Sorting
Use a comparison function that returns the difference between two numbers:
var arrayOfIntegers = [67, 45, 98, 52];
arrayOfIntegers.sort(function (first, second) {
return first - second;
});
console.log("Ascending order:", arrayOfIntegers);
Ascending order: [ 45, 52, 67, 98 ]
Descending Order
To sort in descending order, reverse the subtraction:
var numbers = [67, 45, 98, 52];
numbers.sort(function (first, second) {
return second - first;
});
console.log("Descending order:", numbers);
Descending order: [ 98, 67, 52, 45 ]
Using Arrow Functions
Modern JavaScript allows shorter syntax with arrow functions:
var numbers = [23, 1, 78, 45];
console.log("Ascending:", numbers.sort((a, b) => a - b));
console.log("Descending:", numbers.sort((a, b) => b - a));
Ascending: [ 1, 23, 45, 78 ] Descending: [ 78, 45, 23, 1 ]
How the Comparison Function Works
The comparison function returns:
- Negative value: first element comes before second
- Zero: elements are equal
- Positive value: first element comes after second
Conclusion
Always use a comparison function (a, b) => a - b when sorting integers in JavaScript. The default sort() method treats numbers as strings, leading to incorrect results.
