I've got an array of question and different answers (which I build dynamically, so the number of entries and different answers can vary):
var qaArray = [
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
]
I need a function to build another array object from this, which would hold the 'answer' and 'count', in this case it would be:
[
{ answer: "Answer A", count: 3 },
{ answer: "Answer B", count: 4 },
{ answer: "Answer C", count: 2 },
]
Is there an easy method to do this, without straight forward loops?
If ES6 is not a problem, it can be done by:
var qaArray = [
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
];
var result = [...new Set(qaArray.map(q => q.answer))].map(a => ({ answer: a, count: qaArray.filter(e => e.answer === a).length }));
console.log(result);
If you are looking for solution without reduce
or forEach
, here is a verbose way using lodash.
_.countBy
will give you close result, but if you want to transform it into array as you want, use mapValues
.
_.chain(qaArray)
.countBy('answer')
.mapValues(function(value, key) {
return { answer: key, count: value }
})
.values()
.value()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With