I searched extensively for solutions online, but I still can't seem to make it work and I'm unsure why.
Here is an array with objects:
array =[
{
"name":"Alex",
"id":0
},
{
"age":20,
"id":0
},
{
"name":"John",
"id":1
},
{
"age":30,
"id":1
}
]
My goal is to group them based on their id, resulting in the following outcome:
array =[
[
{
"name":"Alex",
"id":0
},
{
"age":20,
"id":0
}
],
[
{
"name":"John",
"id":1
},
{
"age":30,
"id":1
}
]
]
I came across several solutions that dealt with a similar problem, so I attempted one, but I can't figure out why it's not functioning as expected.
array.reduce((a, value) => {
a[value.id] = [...a[value.id] || [], value];
return a;
}, [])
If anyone could shed some light on this issue, that would be greatly appreciated.