How to sort an array of JavaScript objects by a string property value?
I have an array of JavaScript objects:
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
How can I sort them by the value of last_nom in JavaScript?
I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?
To sort an array of JavaScript objects by a string property value like last_nom, you can use the Array.prototype.sort() method with a custom compare function that accesses the specific property. The most straightforward approach is to use localeCompare() for proper string comparison, which handles different character sets and case sensitivity automatically.
Contents
- Basic Sorting Approach
- Using localeCompare for Better String Comparison
- Case-Insensitive Sorting
- Advanced Sorting Techniques
- Performance Considerations
- Complete Working Example
Basic Sorting Approach
The fundamental way to sort objects by a property is to provide a compare function to the sort() method. This function takes two parameters (a and b representing the objects being compared) and should return:
- A negative value if a should come before b
- A positive value if a should come after b
- Zero if they are equal
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
// Basic comparison function
objs.sort(function(a, b) {
if (a.last_nom < b.last_nom) {
return -1;
}
if (a.last_nom > b.last_nom) {
return 1;
}
return 0;
});
This approach works but has limitations with string comparison, particularly when dealing with different cases or special characters.
Using localeCompare for Better String Comparison
For robust string comparison, use the localeCompare() method which provides proper linguistic sorting according to the current locale:
objs.sort(function(a, b) {
return a.last_nom.localeCompare(b.last_nom);
});
// Or with arrow function syntax (ES6+)
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
The localeCompare() method is specifically designed for string comparison and handles:
- Different character sets (including Unicode)
- Proper alphabetical ordering
- Case sensitivity according to locale rules
Case-Insensitive Sorting
If you want to sort regardless of case, convert both strings to the same case before comparison:
objs.sort(function(a, b) {
var lastNomA = a.last_nom.toLowerCase();
var lastNomB = b.last_nom.toLowerCase();
return lastNomA.localeCompare(lastNomB);
});
// More concise version
objs.sort((a, b) => a.last_nom.toLowerCase().localeCompare(b.last_nom.toLowerCase()));
This ensures that “jamf”, “Bodine”, and “Prentice” are sorted correctly regardless of their original case.
Advanced Sorting Techniques
Multi-Level Sorting
You can sort by multiple properties by chaining comparisons:
// Sort by last_nom, then by first_nom if last_nom is the same
objs.sort((a, b) => {
const lastNameCompare = a.last_nom.localeCompare(b.last_nom);
if (lastNameCompare !== 0) return lastNameCompare;
return a.first_nom.localeCompare(b.first_nom);
});
Dynamic Property Sorting
Create a reusable function that can sort by any property:
function sortByProperty(array, property, direction = 'asc') {
return array.sort((a, b) => {
const aVal = a[property];
const bVal = b[property];
if (typeof aVal === 'string' && typeof bVal === 'string') {
const comparison = aVal.localeCompare(bVal);
return direction === 'asc' ? comparison : -comparison;
}
return direction === 'asc' ? aVal - bVal : bVal - aVal;
});
}
// Usage
sortByProperty(objs, 'last_nom');
sortByProperty(objs, 'first_nom', 'desc');
Schwartzian Transform (Decorate-Sort-Undecorate)
For better performance with complex objects, you can use the Schwartzian transform pattern:
function sortByAttribute(array, ...attrs) {
return array
.map(obj => {
const decorated = attrs.map(attr => {
const descending = attr.charAt(0) === '-';
const property = descending ? attr.substring(1) : attr;
return {
value: obj[property],
descending
};
});
return { obj, decorated };
})
.sort((a, b) => {
for (let i = 0; i < a.decorated.length; i++) {
const { value: valA, descending: descA } = a.decorated[i];
const { value: valB, descending: descB } = b.decorated[i];
if (valA < valB) return descA ? 1 : -1;
if (valA > valB) return descA ? -1 : 1;
}
return 0;
})
.map(({ obj }) => obj);
}
// Usage
sortByAttribute(objs, 'last_nom', 'first_nom');
Performance Considerations
When working with large arrays, consider these performance tips:
- Avoid creating new arrays unnecessarily - The
sort()method modifies the array in place - Use simple compare functions - Complex logic in compare functions can slow down sorting
- Consider pre-sorting - If the array changes infrequently but is sorted frequently, maintain a sorted copy
- Use stable algorithms - JavaScript’s sort is stable, meaning equal elements maintain their original order
Complete Working Example
Here’s a complete, practical example showing how to sort your specific array:
// Your original array
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
console.log('Original array:', objs);
// Sort by last_nom using localeCompare
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
console.log('Sorted by last_nom:', objs);
// Output:
// Original array: [
// { first_nom: 'Laszlo', last_nom: 'Jamf' },
// { first_nom: 'Pig', last_nom: 'Bodine' },
// { first_nom: 'Pirate', last_nom: 'Prentice' }
// ]
// Sorted by last_nom: [
// { first_nom: 'Pig', last_nom: 'Bodine' },
// { first_nom: 'Laszlo', last_nom: 'Jamf' },
// { first_nom: 'Pirate', last_nom: 'Prentice' }
// ]
Important note: You do NOT need to add a toString() method to your objects. The sort() method works perfectly with custom compare functions that access object properties directly.
Sources
- Array.prototype.sort() - JavaScript | MDN
- How to Sort an Array of Objects by Property Name in JavaScript - freeCodeCamp
- JavaScript Program to Sort Array of Objects by Property Values - Programiz
- Sort Array of Objects by String Property Value - Stack Abuse
- How to sort an array of objects by property values ? - GeeksforGeeks
- Sort an Array of Objects in JavaScript - Scaler Topics
Conclusion
Sorting JavaScript objects by string property values is straightforward once you understand the compare function mechanism. The key takeaways are:
- Use
Array.prototype.sort()with a custom compare function that accesses the specific property you want to sort by - Prefer
localeCompare()for string comparisons as it handles edge cases better than simple comparison operators - Convert to lowercase for case-insensitive sorting when needed
- You don’t need to modify your objects - the compare function can access properties directly
- Consider performance implications when working with large datasets or complex sorting logic
The most practical approach for your specific case would be:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
This single line will sort your array objects by the last_nom property in ascending alphabetical order, handling all the string comparison complexities automatically.