I have an array like this:
const test = [
{
label: "C",
options: [
{ label: "C"},
{ label: "B"}
]
},
{
label: "A",
options: [
{ label: "Z"},
{ label: "Y"}
]
},
{
label: "B",
options: [
{ label: "J"},
{ label: "H"}
]
},
{
label: "D",
options: [
{ label: "T"},
{ label: "B"}
]
}
]
I need to sort alphabetically this array in two ways:
1) By the first label (outside the options array)
2) And the options by label
I only managed to sort by the first label so far, using this example:
function compareStrings(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
test.sort(function (a, b) {
return compareStrings(a.label, b.label)
})
How can I order the options inside as well?
The expected output array would be:
const test_SORTED = [
{
label: "A",
options: [
{ label: "B"},
{ label: "C"}
]
},
{
label: "B",
options: [
{ label: "Y"},
{ label: "Z"}
]
},
{
label: "C",
options: [
{ label: "H"},
{ label: "J"}
]
},
{
label: "D",
options: [
{ label: "B"},
{ label: "T"}
]
}
]