1👍
✅
This outputs an array of arrays of objects, instead of multiple array variables of objects. Since JavaScript objects preserve insertion order, you don’t need to worry about the questions being out of order, assuming they’re already in the proper order.
const data = [{question1:"Apple",question2:5,question3:"Item 1"},{question1:"Apple",question2:4,question3:"Item 2"},{question1:"Orange",question2:4,question3:"Item 2"}];
const newData = Object.values(data.reduce((acc, qna) => {
for (const [question, answer] of Object.entries(qna)) {
acc[question] = acc[question] ?? {};
acc[question][answer] = (acc[question][answer] ?? 0) + 1;
}
return acc;
}, {}))
.map((answerCount) => Object.entries(answerCount)
.map(([answer, count]) => ({ answer, count }))
);
console.log(newData);
Source:stackexchange.com