you would have to do something like this:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
note: changing the case (to upper or lower) ensures a case insensitive sort.
Answer from Omer Bokhari on Stack Overflowyou would have to do something like this:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
note: changing the case (to upper or lower) ensures a case insensitive sort.
To support unicode:
objArray.sort(function(a, b) {
return a.DepartmentName.localeCompare(b.DepartmentName);
});
Example
JavaScript Array of Objects Sorting: How to Sort by a Specific Object Property
javascript - Sort objects in an array alphabetically based on one property - Stack Overflow
How do I sort an object alphabetically?
Object keys have a traversal order. Integer keys are always first, and are sorted in an ascending order, whereas with non-integer keys, the order of assignment is preserved. However, this means that sorting will only work on non integer keys, because they are always 1st, and always sorted in an ascending order.
With non-numeric keys like this, you could sort it using entries:
const customers = {
"_1": "Joe Shmo",
"_2": "Carrot Top",
"_3": "Nicolas Cage"
};
const customersArr = Object.entries(customers);
let sorted = customersArr.sort((a, b) => a[1].localeCompare(b[1]));
sorted = Object.fromEntries(sorted);But, this is really the wrong data-type if you want consistent and easy sorting. Use an array of objects like this and the sorting is much easier.
const customers = [
{
id: 1,
name: "Joe Shmo"
},
{
id: 2,
name: "Carrot Top"
},
{
id: 3,
name: "Nicolas Cage"
}
];
const sorted = customers.sort((a, b) => a.name.localeCompare(b.name)); More on reddit.com