You codes are a little close to the goal, just need to adjust something.
Please see the comment in below demo:
When acc.find
doesn't find anything, then push one element {name:d.name, data: [value]}
if found, then push one {value: ...}
into data property.
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 };
const value = { value: d.value, count: d.count }; // the element in data property
if (!found) {
//acc.push(...value);
acc.push({name:d.name, data: [value]}) // not found, so need to add data property
}
else {
//acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
found.data.push(value) // if found, that means data property exists, so just push new element to found.data.
}
return acc;
}, []);
console.log(result)