我有一系列问题和不同的答案(我是动态构建的,因此条目数和不同答案可能会有所不同):
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"},
]
我需要一个函数来构建另一个数组对象,这将保留答案'和'计算',在这种情况下它将是:
[
{ answer: "Answer A", count: 3 },
{ answer: "Answer B", count: 4 },
{ answer: "Answer C", count: 2 },
]
有没有一种简单的方法可以做到这一点,没有直接循环?
答案 0 :(得分:3)
如果ES6不是问题,可以通过以下方式完成:
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);
答案 1 :(得分:2)
如果您正在寻找没有reduce
或forEach
的解决方案,请使用lodash进行详细说明。
_.countBy
会为您提供贴近的结果,但如果您想根据需要将其转换为数组,请使用mapValues
。
_.chain(qaArray)
.countBy('answer')
.mapValues(function(value, key) {
return { answer: key, count: value }
})
.values()
.value()
答案 2 :(得分:2)
您可以使用reduce
。如果元素不存在则将元素推送到累加器,如果存在则递增count
。
请找到以下解决方案
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"},
]
result = qaArray.reduce((acc, item) => {
var exist = acc.find(x => x.answer === item.answer);
if (exist) {
exist.count += 1;
} else {
acc.push({
answer: item.answer,
count: 1
})
}
return acc;
}, []);
console.log(result);

答案 3 :(得分:1)
您可以使用Map
来确定答案,然后reduce
对数据进行处理以获取计数,如下所示:
var result = Array.from(qaArray.reduce((acc, { answer }) => {
const current = acc.get(answer) || { answer, count: 0 };
current.count++;
return acc.set(answer, current);
}, new Map()).values());
console.log(result);