Suppose you have an array like this -
[
{
name: "abc",
value: "1"
},
{
name: "xyz",
value: "2"
},
{
name: "abc",
value: "3"
},
{
name: "abc",
value: "4"
},
{
name: "xyz",
value: "5"
},
]
The goal is to transform this array into a single object where values with the same names are grouped together in an array. The desired output should look like this -
{
abc: [1, 3, 4],
xyz: [2, 5]
}
How can we achieve this using the reduce
method in JavaScript?
I attempted a solution, but it didn't produce the expected result. Here's what I tried:
const data = arr.reduce((acc, item) => {
return {
...acc,
[item.name]: [item.value, acc[item.value]]
};
});