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 on multiple columns using JavaScript?
An array with multiple columns is an array that contains multiple elements at each index position. In other words, it's an array of arrays where each sub-array represents a row with multiple column values that need to be sorted based on specific criteria.
In this article, we'll learn how to sort arrays with multiple columns using JavaScript's sort() method combined with custom comparator functions. We'll explore different sorting strategies for various data types.
Basic Syntax
The fundamental approach uses a custom comparator function with the sort() method:
array.sort((a, b) => {
// Compare elements and return:
// -1 if a should come before b
// 1 if a should come after b
// 0 if they are equal
});
Sorting by Single Column
Let's start with a simple example of sorting by one column:
<!DOCTYPE html>
<html>
<body>
<h3>Sorting by Age (Numeric Column)</h3>
<p id="original"></p>
<p id="sorted"></p>
<script>
let people = [
["John", 25],
["Alice", 30],
["Bob", 20],
["Diana", 35]
];
document.getElementById("original").innerHTML =
"Original: " + JSON.stringify(people);
// Sort by age (second column, index 1)
people.sort((a, b) => a[1] - b[1]);
document.getElementById("sorted").innerHTML =
"Sorted by age: " + JSON.stringify(people);
</script>
</body>
</html>
Sorting by Multiple Columns
For multi-column sorting, we can chain comparisons. First sort by primary column, then by secondary column if primary values are equal:
<!DOCTYPE html>
<html>
<body>
<h3>Multi-Column Sorting</h3>
<div id="results"></div>
<script>
let employees = [
["John", "Engineering", 75000],
["Alice", "Engineering", 80000],
["Bob", "Marketing", 65000],
["Diana", "Engineering", 75000],
["Charlie", "Marketing", 70000]
];
let results = document.getElementById("results");
results.innerHTML = "<p>Original: " + JSON.stringify(employees) + "</p>";
// Sort by Department (index 1), then by Salary (index 2)
employees.sort((a, b) => {
// First, compare by department
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
// If departments are equal, compare by salary
return b[2] - a[2]; // Descending order for salary
});
results.innerHTML += "<p>Sorted by Department, then Salary (desc): " +
JSON.stringify(employees) + "</p>";
</script>
</body>
</html>
Interactive Example
Here's an interactive example where you can add data and sort by different columns:
<!DOCTYPE html>
<html>
<body>
<h3>Interactive Multi-Column Sorting</h3>
<input type="text" id="name" placeholder="Name">
<input type="number" id="age" placeholder="Age">
<button onclick="addPerson()">Add Person</button><br><br>
<button onclick="sortByName()">Sort by Name</button>
<button onclick="sortByAge()">Sort by Age</button>
<button onclick="sortByNameThenAge()">Sort by Name, then Age</button><br><br>
<div id="display"></div>
<script>
let people = [];
function addPerson() {
let name = document.getElementById("name").value;
let age = parseInt(document.getElementById("age").value);
if (name && age) {
people.push([name, age]);
document.getElementById("name").value = "";
document.getElementById("age").value = "";
displayPeople();
}
}
function displayPeople() {
let display = document.getElementById("display");
display.innerHTML = "<h4>Current Data:</h4>";
people.forEach(person => {
display.innerHTML += `<p>${person[0]} - ${person[1]} years old</p>`;
});
}
function sortByName() {
people.sort((a, b) => a[0].localeCompare(b[0]));
displayPeople();
}
function sortByAge() {
people.sort((a, b) => a[1] - b[1]);
displayPeople();
}
function sortByNameThenAge() {
people.sort((a, b) => {
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return a[1] - b[1]; // If names are equal, sort by age
});
displayPeople();
}
// Add some initial data
people = [["John", 25], ["Alice", 30], ["Bob", 20], ["Alice", 25]];
displayPeople();
</script>
</body>
</html>
Comparison of Sorting Methods
| Sorting Type | Use Case | Comparator Function |
|---|---|---|
| Numeric Ascending | Sort by age, price, score | (a, b) => a[index] - b[index] |
| Numeric Descending | Highest to lowest values | (a, b) => b[index] - a[index] |
| String Alphabetical | Sort by name, category | (a, b) => a[index].localeCompare(b[index]) |
| Multi-Column | Primary then secondary sorting | Chain multiple comparisons |
Advanced Sorting Example
For complex sorting scenarios, you can create reusable functions:
// Generic multi-column sorting function
function multiSort(array, sortConfig) {
return array.sort((a, b) => {
for (let config of sortConfig) {
let { column, direction = 'asc', type = 'string' } = config;
let result = 0;
if (type === 'number') {
result = a[column] - b[column];
} else {
result = a[column].localeCompare(b[column]);
}
if (direction === 'desc') result *= -1;
if (result !== 0) return result;
}
return 0;
});
}
// Example usage
let data = [
["John", "Engineering", 75000],
["Alice", "Engineering", 80000],
["Bob", "Marketing", 65000]
];
let sorted = multiSort(data, [
{ column: 1, type: 'string' }, // Sort by department first
{ column: 2, type: 'number', direction: 'desc' } // Then by salary descending
]);
console.log(sorted);
[ [ 'Alice', 'Engineering', 80000 ], [ 'John', 'Engineering', 75000 ], [ 'Bob', 'Marketing', 65000 ] ]
Conclusion
Multi-column sorting in JavaScript is achieved by using custom comparator functions with the sort() method. For complex scenarios, chain multiple comparison criteria and return appropriate values (-1, 0, 1) to control the sorting order effectively.
