I have the following array:
const items = [
{ name: 'john', class: 'one', section: 'a' },
{ name: 'john2', class: 'one', section: 'b' },
{ name: 'john3', class: 'one', section: 'a' },
{ name: 'john4', class: 'two', section: 'a' },
{ name: 'john5', class: 'two', section: 'b' },
{ name: 'john6', class: 'two', section: 'b' },
{ name: 'john7', class: 'three', section: 'a' },
{ name: 'john8', class: 'four', section: 'a' },
{ name: 'john9', class: 'four', section: 'b' }
];
I would like to have it grouped in this way:
[
{
'oneA': [
{ name: 'john', class: 'one', section: 'a' },
{ name: 'john3', class: 'one', section: 'a' }
]
},
{
'oneB': [
{ name: 'john2', class: 'one', section: 'b' }
]
},
{
'twoA': [
{ name: 'john4', class: 'two', section: 'a' }
]
},
{
'twoB': [
{ name: 'john5', class: 'two', section: 'b' },
{ name: 'john6', class: 'two', section: 'b' }
]
},
{
'threeA': [
{ name: 'john7', class: 'three', section: 'a' }
]
},
{
'fourA': [
{ name: 'john8', class: 'four', section: 'a' }
]
},
{
'fourB': [
{ name: 'john9', class: 'four', section: 'b' }
]
}
]
I have tried something like this:
items.sort(function (a, b) {
if (a.class > b.class) return 1;
if (a.class < b.class) return -1;
if (a.section > b.section) return 1;
if (a.section < b.section) return -1;
})
This orders the array as I want but it is not grouping as I described above. Do you know a way to reach that?