How to sort an array of objects in JavaScript?
Source: Dev.to
Sorting an array of objects is something you’ll run into pretty often when working with JavaScript. This usually comes up when dealing with tables, lists, or data coming from an API.
In most applications, data doesn’t arrive in the order you want. API responses, database results, or user‑generated content are usually unsorted, so you have to handle that yourself before showing anything on the screen. Sorting becomes especially useful when rendering table rows, listing products by name or price, or showing users alphabetically. A small detail like correct ordering can make a UI feel much easier to use and helps prevent bugs.
sort() Method
JavaScript’s Array.prototype.sort() method reorders the elements of an array. When you’re sorting objects, you provide a comparison function that tells JavaScript how two items should be compared.
The comparison function receives two elements and returns:
- a negative value →
acomes beforeb - a positive value →
bcomes beforea 0→ no change in order
array.sort((a, b) => {
// return negative, positive, or 0
});
Note:
sort()mutates the original array. This often catches people off guard, especially when working with state or reused data.
Most of the time, you won’t sort objects directly. Instead, you’ll sort based on one of their properties like a name, price, or date.
Sorting by String Properties
Common when dealing with names, titles, or labels.
Basic string sorting
users.sort((a, b) => a.name.localeCompare(b.name));
Case‑insensitive sorting
users.sort((a, b) =>
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
);
Descending order
users.sort((a, b) => b.name.localeCompare(a.name));
Using localeCompare() is generally safer than manual string comparisons and gives more consistent results.
Sorting by Numeric and Date Properties
Numeric sorting
products.sort((a, b) => a.price - b.price);
Sorting date strings
Convert date strings to Date objects before comparing:
events.sort((a, b) => new Date(a.date) - new Date(b.date));
This avoids incorrect ordering that can happen with plain string comparison.
Reusable Sort Helper
Writing a new comparison function for every field can become repetitive. A small utility function can simplify the process:
function sortBy(key, order = "asc") {
return (a, b) => {
if (typeof a[key] === "string") {
return order === "asc"
? a[key].localeCompare(b[key])
: b[key].localeCompare(a[key]);
}
// Assume numeric or Date values
return order === "asc"
? a[key] - b[key]
: b[key] - a[key];
};
}
Usage
users.sort(sortBy("name"));
products.sort(sortBy("price", "desc"));
If you need to keep the original array intact:
const sortedUsers = [...users].sort(sortBy("name"));
Things to Keep in Mind
- Avoid mutating the original array when you still need the unsorted data elsewhere.
- Prefer
localeCompare()for string sorting instead of custom logic. - Handle missing or undefined values gracefully to avoid runtime errors.
- Be cautious with mixed types (e.g., numbers stored as strings) – ensure consistent types before comparing.
Conclusion
Sorting arrays of objects is a regular part of working with JavaScript. Once you understand how sort() and comparison functions work, most use cases are straightforward. For simple needs, a direct sort() call is enough. As projects grow, a reusable sort helper can make your code cleaner and easier to maintain, allowing you to handle real‑world data without overcomplicating things.