由于我没有 50 个声誉,因此我无法在此处的同一篇文章中提出问题 ( Remove Duplicate and Count only one in a y:axis )。
我正在开发一个类似的项目,帖子 ( Remove Duplicate and Count only one in a y:axis ) 上的所有内容看起来都不错。输出也很完美,但是,我需要在输出中添加一项额外的内容。
当前输入:
var list = [
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:1,label:'Computers'},
{y:0,label:'Math'},
{y:0,label:'Math'},
{y:1,label:'Math'},
{y:1,label:'Math'},
]
我已经得到的是:
[{y: 1, label: "Computers"}, {y: 2, label: "Math"}]
这对我来说是完美的,我提到的 URL 上的这个解决方案,跳过零,删除重复项..我需要所有这些,我不需要对这些进行任何更改,但是,如果一个主题的所有值都是零然后我希望输出显示零的单个输出。为了清楚起见,下面是我的输入和
新输入: 如果“计算机”的所有值都是 y:为零,那么我希望输出至少告诉我它全部为零。
var list = [
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:0,label:'Computers'}, //here all the values are zero for computers
{y:0,label:'Math'},
{y:0,label:'Math'},
{y:1,label:'Math'},
{y:1,label:'Math'},
]
当前输出:
[{y: 2, label: "Math"}] //this is perfect but, with skip of zeros, I need an output like the below expected output
预期输出:
[{y: 0, label: "Computers"}, {y: 2, label: "Math"}]
最佳答案
如果我理解正确(您想计算每个标签
的正y
值的数量),这应该可以做到
var data = [
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:0,label:'Computers'},
{y:0,label:'Computers'}, //here all the values are zero for computers
{y:0,label:'Math'},
{y:0,label:'Math'},
{y:1,label:'Math'},
{y:2,label:'Math'},
]
var output = data.reduce(function(acc, val){
if (val.label in acc) {
acc[val.label].y += 1 ? val.y > 0 : 0;
} else {
acc[val.label] = {y: 1 ? val.y > 0 : 0, label:val.label};
}
return acc;
}, {});
// and to make it into an array of results
var res = [];
for (var key in output) {
res.push(output[key]);
}
// [{y:0, label:'Computers'}, {y:2, label:'Math'}]
但是,如果您关心 y
的值并希望使用它们的总和,则稍作修改即可解决问题
var output = data.reduce(function(acc, val){
if (val.label in acc) {
acc[val.label].y += val.y;
} else {
acc[val.label] = {y:val.y, label:val.label};
}
return acc;
}, {});
var res = [];
for (var key in output) {
res.push(output[key]);
}
// [{y:0, label:'Computers'}, {y:3, label:'Math'}]
Reduce我认为这里很好,因为它有一个累加器(它记住的变量)并对数组的所有元素使用一个函数。
使用reduce,我们有一个累加器对象{}
(初始值)并向其中添加我们的标签,{'Math':{y:x, label:'Math'} , ..}
并根据我们的数据增加它们的 y
值。仅当这是所需的输出格式时才需要将其放入数组的最后一步,所有结果都在 output
变量中。
查看 Hendry的回答,也许减少是矫枉过正了。但至少是一个有趣的练习。
关于javascript - 跳过零,但将标签值显示为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725631/