You're not far off. This would be a simple change to two lines of your code to achieve it:
const arr = [
{name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
{name: "survey with select", value: "survey with select answer", count: 2},
{name: "werasd", value: "Donald", count: 1},
{name: "werasd", value: "Jim", count: 1}
];
const result = arr.reduce((acc, d) => {
const found = acc.find(a => a.name === d.name);
const value = { name: d.name, val: d.value };
if (found) {
found.data.push(value);
}
else {
acc.push({ name: d.name, data: [{ value: d.value, count: d.count }] });
}
return acc;
}, []);
console.log(result)
Here are the differences:
- acc.push(...value);
+ found.data.push(value);
- acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
+ acc.push({ name: d.name, data: [{ value: d.value, count: d.count }] });