“Sort Array of Objects in JavaScript by Property” can seem a bit daunting if you’re just dipping your toes into coding, can’t it? JavaScript, one of the most popular programming languages, often involves manipulating data stored in arrays. Today’s post will unravel the mystery of sorting arrays of objects in JavaScript by property. We’ll simplify the concept step by step, making it easy to follow. Stick around, and you’ll soon be sorting like a pro!
Why Sorting Arrays of Objects is Common in JavaScript?
Sorting arrays of objects is a routine task in modern JavaScript applications. Whether you’re working on the front end or back end, sorted data helps deliver a better user experience and enables clearer data analysis.
Use Cases Where Sorting is Essential
- Dashboards – Sort data by performance metrics like revenue, user count, or completion rate.
- Leaderboards – Rank users based on scores or time taken.
- Reports – Organize financial data or inventory by date, value, or category.
- Data Grids/Tables – Allow dynamic sorting when users click column headers.
- E-commerce – Sort products by price, rating, or popularity.
In all these scenarios, sorting ensures that users can quickly find and understand the most relevant information.
Common Property Types Used for Sorting
- Strings – e.g., sorting names alphabetically or products by category.
- Numbers – e.g., sorting by price, quantity, or rank.
- Dates – e.g., arranging posts or transactions from newest to oldest.
No matter the data structure, JavaScript offers a flexible and efficient way to sort objects based on any property type.
Basic Syntax – sort()
Method in JavaScript
JavaScript provides the built-in Array.prototype.sort()
method to sort elements of an array. This method can also be extended to sort arrays of objects using custom compare functions.
How sort()
Works on Basic Arrays
By default, the sort()
method converts elements to strings and sorts them in lexicographical (dictionary) order.
javascriptCopyEditconst fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry']
However, this default behavior may not work as expected for numbers:
javascriptCopyEditconst numbers = [10, 2, 30];
numbers.sort();
console.log(numbers); // Output: [10, 2, 30] – incorrect for numeric sorting
That’s because sort()
treats numbers as strings ("10"
, "2"
, "30"
) and compares their character codes.
Using Compare Functions for More Control
To properly sort numbers or object properties, you need to provide a compare function:
javascriptCopyEditnumbers.sort((a, b) => a - b);
console.log(numbers); // Output: [2, 10, 30]
Sorting Arrays in JavaScript
javascript const arrayOfObjects = [ { name: 'Jane', age: 30 }, { name: 'John', age: 25 }, { name: 'Alice', age: 28 } ]; arrayOfObjects.sort((a, b) => a.age - b.age); console.log(arrayOfObjects);
Explanation of the Code
If you’re diving into sorting arrays of objects in JavaScript, this snippet is a neat example! Here’s a breakdown of what this code does, step by step:
- We start by defining an array called `arrayOfObjects` with three objects. Each object has properties: `name` and `age`.
- The array is then sorted using the `sort()` method. This method requires a comparison function, which we define as an arrow function.
- The arrow function `(a, b) => a.age – b.age` compares objects `a` and `b` based on their `age` properties. It sorts the objects in ascending order by age. If the result is negative, `a` comes before `b`; if positive, `b` comes before `a`.
- Finally, the `console.log(arrayOfObjects);` statement outputs the sorted array to the console, showing the objects in order from youngest to oldest.
Output
[
{ name: 'John', age: 25 },
{ name: 'Alice', age: 28 },
{ name: 'Jane', age: 30 }
]
Sort by Numeric Property
When dealing with numeric data like age, score, or price, the default sort()
method doesn’t work correctly unless you use a comparator function.
Example: Sorting Users by Age
const users = [ { name: 'Alice', age: 32 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 29 } ]; users.sort((a, b) => a.age - b.age); console.log(users); // Output: [ // { name: 'Bob', age: 25 }, // { name: 'Charlie', age: 29 }, // { name: 'Alice', age: 32 } // ]
Explanation of the Comparator
The expression a.age - b.age
:
- Returns a negative value if
a
should come beforeb
- Returns a positive value if
b
should come beforea
- Returns
0
if they’re equal
This results in an ascending sort. For descending order, just swap a
and b
:(b.age - a.age)
Sort by String Property (A–Z and Z–A)
Strings need to be sorted alphabetically, and using .localeCompare()
ensures accuracy, especially for non-English characters.
Example: Sorting Products by Name (A–Z)
const products = [ { name: 'Banana' }, { name: 'Apple' }, { name: 'Cherry' } ]; products.sort((a, b) => a.name.localeCompare(b.name)); console.log(products); // Output: [ // { name: 'Apple' }, // { name: 'Banana' }, // { name: 'Cherry' } // ]
Sorting in Reverse Order (Z–A)
products.sort((a, b) => b.name.localeCompare(a.name));
Using localeCompare()
is better than comparing with >
or <
, as it respects locale-specific rules and handles mixed-case strings more reliably.
Sort by Date Property
Dates are often stored as strings or ISO timestamps, and sorting them requires converting to actual Date
objects.
Example: Sorting Events by Date
const events = [ { title: 'Event A', date: '2024-11-10' }, { title: 'Event B', date: '2023-06-15' }, { title: 'Event C', date: '2025-01-20' } ]; events.sort((a, b) => new Date(a.date) - new Date(b.date)); console.log(events); // Output: [ // { title: 'Event B', date: '2023-06-15' }, // { title: 'Event A', date: '2024-11-10' }, // { title: 'Event C', date: '2025-01-20' } // ]
Sorting dates requires converting each string into a Date
object. This enables accurate comparison based on time, not text.
Dynamic Sorting by Property Name (Reusable Function)
Hardcoding the property name every time you sort can become repetitive. A reusable function makes your code cleaner and more flexible.
Reusable Function to Sort by Any Property
function sortByKey(array, key) { return array.sort((a, b) => { if (a[key] < b[key]) return -1; if (a[key] > b[key]) return 1; return 0; }); }
Example Usage
sortByKey(users, 'age'); sortByKey(products, 'name');
This utility function can sort by any key, whether it’s a string, number, or even a date (if dates are pre-converted). For descending order, you can extend the function with an optional order
parameter.
Sorting Arrays in JavaScript: Real-Life Applications
- Inventory Management: Many e-commerce companies rely on sorting algorithms to organise their vast inventory. For instance, a retailer like Amazon might use JavaScript to sort their product database by price, ensuring customers easily find the cheapest or most expensive options first. This sorting helps in presenting products in a user-friendly manner, ultimately enhancing the shopping experience.
- Employee Directory: Companies often have internal directories where they maintain lists of employees. A tech firm, for example, could use JavaScript to sort employees by their last name or department. This not only streamlines internal communications but also simplifies navigation when tracking personnel changes or updating HR records.
- Data Visualisation: Brands specialising in data analytics might sort arrays of objects to generate visual reports. Imagine a startup that analyses social media metrics. They might use JavaScript to sort posts by engagement metrics, such as likes or shares, helping their clients understand what content resonates most with their audience.
- Customer Support Tickets: Companies with customer service operations might use sorting to manage and prioritise support tickets. For example, a SaaS company could sort tickets by urgency or time of submission, ensuring that critical issues are addressed promptly and efficiently.
Handling Edge Cases
Sorting might seem straightforward, but real-world data often comes with quirks—like missing values or mixed casing. Let’s look at how to handle common edge cases while sorting arrays of objects in JavaScript.
1. Sorting with null
or undefined
Values
When an object’s property might be null
or undefined
, it can break or mislead the sorting logic.
Example: Some Users Have No Age
const users = [ { name: 'Alice', age: 32 }, { name: 'Bob' }, { name: 'Charlie', age: 29 } ]; users.sort((a, b) => { if (a.age == null) return 1; // move null/undefined to the end if (b.age == null) return -1; return a.age - b.age; });
This way, users with missing age
values are sorted at the end instead of being placed randomly.
2. Case-Insensitive Sorting for Strings
Default string sorting is case-sensitive, so 'Apple'
comes before 'banana'
, which can be confusing. To make it case-insensitive, convert both values to lowercase before comparing:
products.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()) );
This ensures 'Apple'
, 'banana'
, and 'Cherry'
are sorted in natural alphabetical order, regardless of letter casing.
3. Stable Sort in JavaScript (ES2019+)
A stable sort preserves the original order of elements that compare as equal. For example, if two users have the same age, a stable sort ensures the one who appeared first stays first.
const users = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 30 } ]; users.sort((a, b) => a.age - b.age);
Before ES2019, JavaScript did not guarantee stability across all engines. But now, most modern browsers fully support stable sorting via Array.prototype.sort()
.
This is especially useful when:
- You sort a list multiple times by different properties.
- You want to preserve original input order for tied values.
Handling these edge cases ensures your sorting logic is reliable, even when dealing with messy or inconsistent data.
With our AI-powered js online compiler, users can instantly write, run, and test their code effortlessly. It’s like having a smart assistant by your side that understands your coding needs and provides immediate feedback. Dive into coding with ease and confidence using our advanced tool!
Conclusion
“Sort Array of Objects in JavaScript by Property” enhances your coding toolkit, enabling more efficient data handling. Accomplishing it boosts both confidence and skillset. Give it a go and enjoy the achievement! For more on programming languages like Java, Python, and more, visit Newtum.
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.