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', last_nom: 'Prentice' }
]
Why localeCompare() is useful
localeCompare() is designed for comparing strings alphabetically.
console.log('Bodine'.localeCompare('Jamf')); // negative number
console.log('Prentice'.localeCompare('Jamf')); // positive number
console.log('Jamf'.localeCompare('Jamf')); // 0
Simpler manual comparison
You can also write:
objs.sort((a, b) => {
if (a.last_nom < b.last_nom) return -1;
if (a.last_nom > b.last_nom) return 1;
return 0;
});
This works, but localeCompare() is shorter and clearer for strings.
Descending order
objs.sort((a, b) => b.last_nom.localeCompare(a.last_nom));
Case-insensitive sorting
objs.sort((a, b) =>
a.last_nom.toLowerCase().localeCompare(b.last_nom.toLowerCase())
);
This is helpful when values may contain mixed uppercase and lowercase letters.
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: 'Laszlo', last_nom: 'Jamf' } -
It evaluates:
'Bodine'.localeCompare('Jamf') -
That returns a negative number, so
Bodineshould come beforeJamf. -
If it compares
PrenticewithJamf, the result is positive, soPrenticegoes afterJamf. -
After enough comparisons, the array becomes alphabetically ordered by
last_nom.
Final result:
[
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
]
Important detail: sort() usually modifies the original array.
If you want a sorted copy instead, do this:
const sortedObjs = [...objs].sort((a, b) => a.last_nom.localeCompare(b.last_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: 'JavaScript Basics' },
{ title: 'APIs for Beginners' },
{ title: 'Arrays Explained' }
];
posts.sort((a, b) => a.title.localeCompare(b.title));
This improves readability and gives users predictable output.
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
In many codebases, especially with React or state management, mutation is avoided.
const sortedPeople = [...people].sort((a, b) => a.name.localeCompare(b.name));
Multi-level sorting
If two last names are the same, developers often add a fallback.
const people = [
{ first_nom: 'Anna', last_nom: 'Smith' },
{ first_nom: 'Bob', last_nom: 'Smith' },
{ first_nom: 'Cara', last_nom: 'Adams' }
];
people.sort((a, b) => {
const lastNameResult = a.last_nom.localeCompare(b.last_nom);
if (lastNameResult !== 0) return lastNameResult;
return a.first_nom.localeCompare(b.first_nom);
});
This pattern is very common in tables, lists, and reports.
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, or0trueandfalseare not a proper comparison result
Fix:
objs.sort((a, b) => {
if (a.last_nom < b.last_nom) return -1;
if (a.last_nom > b.last_nom) return 1;
return 0;
});
Or shorter:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
3. Forgetting that sort() mutates the array
Broken assumption:
const sorted = objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
// objs is also changed
Fix if you want a copy:
const sorted = [...objs].sort((a, b) => a.last_nom.localeCompare(b.last_nom));
4. Not handling missing properties
Broken code:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
If last_nom is missing on some object, this can fail.
Safer version:
objs.sort((a, b) => (a.last_nom ?? '').localeCompare(b.last_nom ?? ''));
5. Using toString() unnecessarily
You do not need to add a custom toString() method just to sort by a property.
Better approach:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
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()) | Case-insensitive sorting | Useful when input has mixed case |
sort() on numbers vs strings vs objects
| Data type | Example compare function |
|---|---|
| Numbers | (a, b) => a - b |
| Strings | (a, b) => a.localeCompare(b) |
| Objects by number property | (a, b) => a.age - b.age |
| Objects by string property | (a, b) => a.last_nom.localeCompare(b.last_nom) |
toString() vs compare function
| Option | Should you use it here? | Why |
|---|---|---|
Add toString() to objects | Usually no | Not the normal way to sort by one property |
| Use compare function | Yes | Lets you choose the exact property to sort by |
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
const sorted = [...objs].sort((a, b) => a.last_nom.localeCompare(b.last_nom));
Safe when property may be missing
array.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
Rules for compare function
- negative:
acomes beforeb - positive:
acomes afterb 0: equal order for sorting
Do not do this
objs.sort();
objs.sort((a, b) => a.last_nom > b.last_nom);
Usually no need for toString()
- Sort by the property directly
- Use a compare callback
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?
Reverse the comparison:
array.sort((a, b) => b.name.localeCompare(a.name));
What if some objects are missing the property?
Use a fallback value:
array.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.