我想比较本周和上周数据的动物数量百分比,但我坚持比较算法。我只能生成数据。
let data = []
for (let i = 0; i < 14; i++) {
let dog_count = _.random(0, 100),
cat_count = _.random(0, 100)
data.push({
date: moment().subtract(i, 'd').format('YYYY-MM-DD'),
total_count: dog_count + cat_count,
dog_count,
cat_count
})
}
我试图实现的输出是这个
...
[{
date: '2017-8-10',
dog: {
percentage: 67,
indicator: 1 //1 means greater, 0 means equal, -1 means lesser
},
cat: {
percentage: 33,
indicator: -1
}]
...
答案 0 :(得分:0)
我使用了部分你的代码并添加了一些想法试图设置你的预期输出。我想这就是你想要的。你可以很多地改进代码,它是在5分钟内完成的。
let data = [];
for (let i = 0; i < 14; i++) {
let dog = [];
let cat = [];
let dog_count = _.random(0, 100),
cat_count = _.random(0, 100)
var total_count = dog_count + cat_count;
var cat_count_perc = cat_count/total_count;
var dog_count_perc = dog_count/total_count;
var cat_int = 0;
var dog_int = 0;
if(dog_count_perc > cat_count_perc)
{
dog_int = 1;
cat_int = -1;
}else if (cat_count_perc > dog_count_perc)
{
dog_int = -1;
cat_int = 1;
}
dog.push({
percentage: dog_count_perc.toFixed(2),
indicator: dog_int
});
cat.push({
percentage: cat_count_perc.toFixed(2),
indicator: cat_int
})
data.push({
date: moment().subtract(i, 'd').format('YYYY-MM-DD'),
dog: dog,
cat: cat
})
}
console.log(data);
jsfiddle :https://jsfiddle.net/xrx2aebx/1/
答案 1 :(得分:0)
这是伪代码
1. Generate last week's data, ordered by date(let lastWeekData)
2. Generate current week's data, ordered by date(let currentWeekData)
3. declare output array(let output = [])
4. for(var i=0;i< currentWeekData.length;i++){
var currentOutput = {date: currentWeekData[i].date, dog: {},cat: {}};
currentOutput.dog.percentage = currentWeekData[i].dog_Count / lastWeekData[i].dog_Count * 100; //here you need to change the percentage formula based on your requirement
currentOutput.cat.percentage = currentWeekData[i].cat_Count / lastWeekData[i].cat_Count * 100;
output.push(currentOutput);
}
相应地更改百分比公式。