I am facing a challenge with 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 want to group it in a specific manner, like this:
[
{
'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 attempted the following solution:
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;
})
While this code successfully orders the array as intended, it does not achieve the desired grouping. Is there an alternative method that can accomplish this?