Question
How to Sort an Array of Objects by a String Property in JavaScript
Question
I have an array of JavaScript objects:
const objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
How can I sort this array by the value of last_nom in JavaScript?
I know about sort(a, b), but it seems to be commonly used with strings and numbers. Can it also be used for objects, or would I need to add a toString() method to my objects?
Short Answer
By the end of this page, you will understand how JavaScript's Array.prototype.sort() works with arrays of objects, how to sort by a specific string property like last_nom, and when to use simple comparisons versus localeCompare() for safer string sorting.
Concept
JavaScript's sort() does not only work on plain strings or numbers. It can sort any array, including arrays of objects, as long as you provide a comparison function.
That comparison function tells JavaScript how to decide the order of two items:
- return a value less than 0 if
ashould come beforeb - return greater than 0 if
ashould come afterb - return 0 if they are considered equal for sorting
When your array contains objects, JavaScript does not automatically know which property matters. So you choose the property yourself.
For string properties such as last_nom, you usually compare:
a.last_nomandb.last_nom
There is no need to add a toString() method. That would not be the normal solution here.
This matters in real programming because data often comes as objects:
- users with names
- products with titles
- API responses with labels
- records with categories
Sorting by object properties is a very common task in frontend and backend JavaScript code.
Mental Model
Think of sort() as asking a referee to compare two players at a time.
If your array contains numbers, the referee can compare the numbers directly. If your array contains objects, the referee asks: which part of the object should I look at?
Your comparison function is the referee's rulebook.
For example:
- compare by
last_nom - if
last_nomis alphabetically earlier, put it first - otherwise put it later
So instead of changing the whole object into a string, you simply tell sort() which label on the object to use.
Syntax and Examples
Basic syntax
array.sort((a, b) => {
// return negative, positive, or 0
});
Sort objects by a string property
const objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
console.log(objs);
Output:
[
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pirate', : }
]
Step by Step Execution
Consider this code:
const objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
Step by step:
-
sort()starts rearranging the array. -
It picks two objects to compare.
-
For each pair, it runs this function:
(a, b) => a.last_nom.localeCompare(b.last_nom) -
Suppose it compares:
a = { first_nom: 'Pig', last_nom: 'Bodine' } b = { first_nom: , : }
Real World Use Cases
Sorting arrays of objects by string properties appears everywhere in JavaScript applications.
Common examples
- User lists: sort users by last name, first name, or username
- Product catalogs: sort products by title or category
- Admin dashboards: sort rows by status, department, or label
- Search results: display matching items alphabetically
- API data processing: sort fetched records before rendering
- File explorers: sort files by name
Example: sorting users before rendering
const users = [
{ id: 1, name: 'Zara' },
{ id: 2, name: 'Ali' },
{ id: 3, name: 'Mina' }
];
const sortedUsers = [...users].sort((a, b) => a.name.localeCompare(b.name));
console.log(sortedUsers);
Example: sorting API response data
const posts = [
{ title: },
{ : },
{ : }
];
posts.( a..(b.));
Real Codebase Usage
In real projects, developers often wrap sorting logic in reusable functions and combine it with validation.
Common pattern: reusable property sorter
function sortByStringProperty(array, property) {
return [...array].sort((a, b) => {
const valueA = a[property] ?? '';
const valueB = b[property] ?? '';
return valueA.localeCompare(valueB);
});
}
const sorted = sortByStringProperty(objs, 'last_nom');
This is useful when many screens need similar sorting.
Guarding against missing values
Real data is often messy. Some objects may not contain the property.
const people = [
{ name: 'Lina' },
{},
{ name: 'Adam' }
];
people.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
Sorting without mutating original data
Common Mistakes
1. Forgetting to compare a property
Broken code:
objs.sort();
Why it is a problem:
sort()without a compare function tries to convert items to strings- for objects, that does not produce useful alphabetical sorting by
last_nom
Fix:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
2. Returning true or false instead of a negative/positive number
Broken code:
objs.sort((a, b) => a.last_nom > b.last_nom);
Why it is a problem:
sort()expects a negative number, positive number, or0trueand are not a proper comparison result
Comparisons
Comparing ways to sort by a string property
| Approach | Example | Good for | Notes |
|---|---|---|---|
localeCompare() | a.name.localeCompare(b.name) | Most string sorting | Clear and designed for strings |
Manual if/else | if (a.name < b.name) return -1 | Learning how sort works | More verbose |
Default sort() | array.sort() | Simple string arrays only | Not suitable for object property sorting |
Convert with toLowerCase() | a.name.toLowerCase().localeCompare(b.name.toLowerCase()) |
Cheat Sheet
Quick reference
Sort objects by string property
array.sort((a, b) => a.property.localeCompare(b.property));
Example
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
Descending order
objs.sort((a, b) => b.last_nom.localeCompare(a.last_nom));
Case-insensitive
objs.sort((a, b) =>
a.last_nom.toLowerCase().localeCompare(b.last_nom.toLowerCase())
);
Avoid mutating original array
FAQ
Can JavaScript sort() sort arrays of objects?
Yes. sort() works on arrays of any values, including objects. For objects, you provide a compare function that tells JavaScript which property to compare.
How do I sort objects alphabetically by a property in JavaScript?
Use a compare function with localeCompare():
array.sort((a, b) => a.name.localeCompare(b.name));
Do I need a toString() method to sort objects?
No. That is not the usual solution. Just compare the property you want, such as a.last_nom and b.last_nom.
Does sort() change the original array?
Yes. sort() mutates the array. If you want a new sorted array, copy first with spread syntax.
What is the best way to sort strings in JavaScript?
For most cases, localeCompare() is the clearest and safest choice for string sorting.
How do I sort in descending alphabetical order?
Mini Project
Description
Build a small contact list sorter. You have an array of contact objects, and you want to display them in alphabetical order by last name. This demonstrates how to sort objects by a string property, how to avoid mutating the original data, and how to add a fallback sort when two contacts share the same last name.
Goal
Create a function that returns a new array of contacts sorted by lastName, and then by firstName when the last names are the same.
Requirements
- Create an array of contact objects with
firstNameandlastName. - Write a function that returns a sorted copy instead of changing the original array.
- Sort primarily by
lastName. - If two contacts have the same
lastName, sort them byfirstName. - Print both the original array and the sorted array.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.