I have seen similar question in stackoverflow, by using reduce method like this post: Javascript – Group by one property of object in an array of objects.
but I would like to get back a result as array []
, instead of an object {}
.
Here is a example
Input:
[
{
"name": "ABC Equity",
"category": "Equity"
},
{
"name": "EBC Bonds",
"category": "Bond"
},
{
"name": "Corporate Bonds",
"category": "Bond"
},
{
"name": "Private Equity",
"category": "Equity"
},
{
"name": "Fixed abc",
"category": "Fixed"
}
]
Expected after regrouping:
[
{
label: 'Equity',
options: [
{ value: 'ABC Equity', label: 'ABC Equity'},
{ value: 'Private Equity', label: 'Private Equity'},
],
},
{
label: 'Bond',
options: [
{ value: 'EBC Bonds', label: 'EBC Bonds'},
{ value: 'Corporate Bonds', label: 'Corporate Bonds' },
],
},
{
label: 'Fixed',
options: [
{ value: 'Fixed abc', label: 'Fixed abc'}
],
},
]
2
Answers
To convert the object created using a reduce, you need to take the values of the object after reducing.
Note the use of nullish coalescing assignment operators
??=
This code is O(n) (runs once over the input)
This should work: