I have data like:
var data =
[{
"date":"1-1-2013",
"answer":"yes"
},{
"date":"1-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":" " //this is not answered!
},,{
"date":"2-1-2013",
"answer":"no"
}];
I need to return[array] percentages of responses for that day(groupedBy
) which have a value of “yes” for the “answer”.
For above the result is: [50, 0...]
I have written this below code, it works but i believe it can be simplified a lot.
var freshData = _.map(data,function(key){
if (key.answer == "") return false;
return key;
});
var reducedData = _.filter(freshData, function(n) {
return n != false;
});
var groups = _.groupBy(reducedData, function(value){
return value.date + '#' + value.answer;
});
var result = _.map(groups,function(key){
if (key[0].answer == "") return false;
return {
date : key[0].date,
answer : key[0].answer,
length :key.length
};
});
var result2 = _.chunk(result,2);
var result3 = _.map(result2,function(key){
return {
date:key[0].date,
yes:key[0].length,
no:key[1].length,
percentage : (key[1].length/(key[0].length + key[1].length) * 100)
}
});
var result4 = _.map(result3,function(key){
return key.percentage;
});
console.log(result4);
I need to use lodash. Thanks.