I have the following array for example -
[
{
name: "abc",
value: "1"
},
{
name: "xyz",
value: "2"
},
{
name: "abc",
value: "3"
},
{
name: "abc",
value: "4"
},
{
name: "xyz",
value: "5"
},
]
Now, I want to reduce this array into a single object by grouping value with the same name together into an array. Something like this -
{
abc: [1, 3, 4],
xyz: [2, 5]
}
How do I do this using reduce in JavaScript?
I'm not sure if this the right approach but I have tried something like this and it doesn't give me the desired output.
const data = arr.reduce((acc, item) => {
return {
...acc,
[item.name]: [item.value, acc[item.value]]
};
});