Sort array of objects by string property value
Categories:
Efficiently Sort Arrays of Objects by String Property in JavaScript

Learn various techniques to sort an array of JavaScript objects based on the value of a specific string property, handling case sensitivity and locale considerations.
Sorting data is a fundamental operation in programming, and JavaScript provides powerful tools for manipulating arrays. When working with arrays of objects, a common requirement is to sort these objects based on the value of one of their properties. This article will guide you through different methods to sort an array of objects by a string property, covering basic sorting, case-insensitive sorting, and locale-aware comparisons.
Understanding JavaScript's Array.prototype.sort()
The sort()
method in JavaScript sorts the elements of an array in place and returns the sorted array. Its default behavior converts elements to strings and compares them in UTF-16 code unit order. However, for sorting numbers or objects, you must provide a compareFunction
.
The compareFunction
takes two arguments, a
and b
, representing two elements from the array. It should return:
- A negative value if
a
should come beforeb
. - A positive value if
a
should come afterb
. 0
ifa
andb
are considered equal for sorting purposes.
flowchart TD A[Start Sort Process] --> B{Compare Function Provided?} B -->|No| C[Default UTF-16 String Sort] B -->|Yes| D[Call compareFunction(a, b)] D --> E{Return Value?} E -->|Negative| F[a comes before b] E -->|Positive| G[a comes after b] E -->|Zero| H[a and b are equal] F --> I[Continue Sorting] G --> I H --> I C --> J[End Sort Process] I --> J
Flowchart of JavaScript's Array.prototype.sort()
mechanism.
Basic Case-Sensitive Sorting by String Property
For a straightforward, case-sensitive sort, you can directly compare the string properties of two objects. This method is simple and efficient when case sensitivity is desired or not a concern.
const products = [
{ name: 'Apple', price: 1.00 },
{ name: 'Banana', price: 0.50 },
{ name: 'Orange', price: 1.20 },
{ name: 'apple', price: 1.10 } // Note the lowercase 'a'
];
// Sort by 'name' property (case-sensitive)
products.sort((a, b) => {
const nameA = a.name;
const nameB = b.name;
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0; // names must be equal
});
console.log(products);
/* Output:
[
{ name: 'Apple', price: 1 },
{ name: 'Banana', price: 0.5 },
{ name: 'Orange', price: 1.2 },
{ name: 'apple', price: 1.1 }
]
*/
Basic case-sensitive sorting of an array of objects by the 'name' property.
sort()
method modifies the array in place. If you need to preserve the original array, create a shallow copy first using [...array].sort()
or array.slice().sort()
.Case-Insensitive Sorting with toLowerCase()
Often, you'll want to sort strings without regard to their case. The simplest way to achieve this is to convert both strings to a consistent case (e.g., lowercase) before comparison using the toLowerCase()
method.
const products = [
{ name: 'Apple', price: 1.00 },
{ name: 'Banana', price: 0.50 },
{ name: 'Orange', price: 1.20 },
{ name: 'apple', price: 1.10 }
];
// Sort by 'name' property (case-insensitive)
products.sort((a, b) => {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
console.log(products);
/* Output:
[
{ name: 'Apple', price: 1 },
{ name: 'apple', price: 1.1 },
{ name: 'Banana', price: 0.5 },
{ name: 'Orange', price: 1.2 }
]
*/
Case-insensitive sorting using toLowerCase()
before comparison.
Locale-Aware Sorting with String.prototype.localeCompare()
For more robust and linguistically correct sorting, especially with international characters, String.prototype.localeCompare()
is the preferred method. It compares two strings in the current locale's sort order and returns a number indicating their relative order.
localeCompare()
can also handle case-insensitivity and numeric sorting through its options object, making it highly versatile.
const products = [
{ name: 'Zebra', price: 10.00 },
{ name: 'apple', price: 1.10 },
{ name: 'Banana', price: 0.50 },
{ name: 'Éclair', price: 2.50 },
{ name: 'orange', price: 1.20 }
];
// Sort by 'name' property using localeCompare (case-insensitive, locale-aware)
products.sort((a, b) => {
return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
});
console.log(products);
/* Output:
[
{ name: 'apple', price: 1.1 },
{ name: 'Banana', price: 0.5 },
{ name: 'Éclair', price: 2.5 },
{ name: 'orange', price: 1.2 },
{ name: 'Zebra', price: 10 }
]
*/
Locale-aware and case-insensitive sorting using localeCompare()
.
sensitivity: 'base'
option in localeCompare()
treats 'a' and 'A' as equivalent, and also ignores accents (e.g., 'e' and 'é' are treated as equivalent for primary sorting). For strict case-insensitivity without ignoring accents, use sensitivity: 'accent'
.Creating a Reusable Sort Function
To avoid repeating the sorting logic, you can create a higher-order function that generates a comparison function for a given property and desired sort order (ascending/descending).
const createSorter = (key, order = 'asc', caseInsensitive = false) => {
return (a, b) => {
let valA = a[key];
let valB = b[key];
if (caseInsensitive) {
valA = typeof valA === 'string' ? valA.toLowerCase() : valA;
valB = typeof valB === 'string' ? valB.toLowerCase() : valB;
}
if (valA < valB) {
return order === 'asc' ? -1 : 1;
}
if (valA > valB) {
return order === 'asc' ? 1 : -1;
}
return 0;
};
};
const items = [
{ id: 1, name: 'Zebra' },
{ id: 2, name: 'apple' },
{ id: 3, name: 'Banana' }
];
// Sort ascending, case-insensitive
items.sort(createSorter('name', 'asc', true));
console.log('Ascending, case-insensitive:', items);
/* Output:
[
{ id: 2, name: 'apple' },
{ id: 3, name: 'Banana' },
{ id: 1, name: 'Zebra' }
]
*/
// Sort descending, case-sensitive
items.sort(createSorter('name', 'desc', false));
console.log('Descending, case-sensitive:', items);
/* Output:
[
{ id: 1, name: 'Zebra' },
{ id: 3, name: 'Banana' },
{ id: 2, name: 'apple' }
]
*/
A reusable higher-order function for flexible sorting.