Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-organize a javascript array of objects

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?

like image 600
Gintas K Avatar asked Jan 30 '23 00:01

Gintas K


2 Answers

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);
like image 123
Faly Avatar answered Feb 05 '23 16:02

Faly


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()
like image 26
emil Avatar answered Feb 05 '23 17:02

emil