跳过零,但将标签值显示为零

时间:2015-06-09 07:31:28

标签: javascript

由于我没有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上,跳过零,删除重复..我需要所有这些,我不需要对这些进行任何更改,但是,如果一个主题的所有值都为零那么我希望输出显示零输出。下面说清楚是我的输入和

新输入: 如果'Computers'的所有值都是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"}]

2 个答案:

答案 0 :(得分:0)

我的香草回答是:

编辑:没有注意到问题是1岁:D

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'},
];

var out = []; 

var filt = {};
for (var entry of list) {
  if (!filt[entry.label]) {
    filt[entry.label] = {y: 0, label: entry.label}
  }
  
  filt[entry.label].y += entry.y;
}

for (var key in filt) {
  out.push(filt[key]);
}

// out is the list you need

document.body.innerHTML = JSON.stringify(out);

答案 1 :(得分:0)

如果我理解正确(您想要计算每个y的正label个值),那么应该这样做

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的回答,也许减少是过度的。但至少是一项有趣的运动。