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 object by two fields in JavaScript?
An array of objects is an array that contains all the elements in the form of JavaScript objects. Here, we are said to use an array of objects with two fields that means, have to use objects with two elements as elements of the array.
In this article, we are going to learn about the method of sorting the array of objects by two fields in JavaScript. We can simply use the sort() method of JavaScript to sort the elements of an array and give it a cmp or the comparator function to define the order in which we want to sort the elements of objects in the given array.
Syntax
Following syntax will show you how to use the sort() method with an array to sort its elements ?
array_name.sort(comparator_function);
Basic Sorting by Single Field
Let's first understand how to sort by a single field using a simple example:
let students = [
{name: "Alice", age: 25, grade: 85},
{name: "Bob", age: 30, grade: 92},
{name: "Charlie", age: 20, grade: 78}
];
// Sort by age (ascending)
students.sort((a, b) => a.age - b.age);
console.log("Sorted by age:", students);
// Sort by grade (descending)
students.sort((a, b) => b.grade - a.grade);
console.log("Sorted by grade:", students);
Sorting by Two Fields (Primary and Secondary)
When sorting by two fields, we sort primarily by the first field, and when values are equal, we sort by the second field:
let employees = [
{department: "IT", salary: 50000},
{department: "HR", salary: 45000},
{department: "IT", salary: 60000},
{department: "HR", salary: 40000},
{department: "IT", salary: 55000}
];
// Sort by department first, then by salary
employees.sort((a, b) => {
// Primary sort: department (alphabetical)
if (a.department < b.department) return -1;
if (a.department > b.department) return 1;
// Secondary sort: salary (ascending) when departments are same
return a.salary - b.salary;
});
console.log("Sorted by department, then salary:");
employees.forEach(emp => console.log(`${emp.department}: $${emp.salary}`));
Compact Sorting with OR Operator
JavaScript's logical OR operator can simplify multi-field sorting:
let products = [
{category: "Electronics", price: 299},
{category: "Books", price: 15},
{category: "Electronics", price: 199},
{category: "Books", price: 25},
{category: "Electronics", price: 399}
];
// Sort by category first, then by price
products.sort((a, b) => {
return a.category.localeCompare(b.category) || a.price - b.price;
});
console.log("Sorted by category, then price:");
products.forEach(product =>
console.log(`${product.category}: $${product.price}`)
);
Interactive Example
Here's an interactive example where you can add objects and see them sorted:
<!DOCTYPE html>
<html>
<body>
<h3>Sort Array of Objects by Two Fields</h3>
<p>Enter values to create objects:</p>
<input type="number" id="field1" placeholder="First Field"><br><br>
<input type="number" id="field2" placeholder="Second Field"><br><br>
<button onclick="addObject()">Add Object</button>
<button onclick="sortObjects()">Sort by First Field, then Second</button>
<p id="display">Objects will appear here</p>
<script>
let objectsArray = [];
function addObject() {
const field1 = parseInt(document.getElementById("field1").value);
const field2 = parseInt(document.getElementById("field2").value);
if (!isNaN(field1) && !isNaN(field2)) {
objectsArray.push({first: field1, second: field2});
document.getElementById("field1").value = "";
document.getElementById("field2").value = "";
displayObjects();
}
}
function sortObjects() {
objectsArray.sort((a, b) => a.first - b.first || a.second - b.second);
displayObjects();
}
function displayObjects() {
const display = document.getElementById("display");
display.innerHTML = objectsArray.map(obj =>
`{first: ${obj.first}, second: ${obj.second}}`
).join(", ");
}
</script>
</body>
</html>
Comparison of Sorting Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| Explicit if-else | High | Good | Complex sorting logic |
| OR operator (||) | Medium | Good | Simple multi-field sorting |
| Chained sorts | Low | Poor | Not recommended |
Key Points
- The comparator function should return -1, 0, or 1 for proper sorting
- Use the OR operator (||) for concise multi-field sorting
- Primary field is sorted first, secondary field breaks ties
- For string sorting, use
localeCompare()method
Conclusion
Sorting arrays of objects by multiple fields is essential for organizing data effectively. The sort() method with custom comparator functions provides flexible control over sorting behavior, whether using explicit conditions or the concise OR operator approach.
