使用JavaScript删除标签重复label:'Adnim'
并仅计算" 1"跳过零和{34; 0" y:1,
y:0,
这是完美的工作,但问题是如果特定标签的所有值都为零,那么对于该实验,它不会给出输出。
实施例:1
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:1,label:'Adnim'},//Value of y:1 is one all are zero
{y:0,label:'Adnim2'},
{y:0,label:'Adnim2'},
{y:1,label:'Adnim2'},
{y:1,label:'Adnim2'},
当前输出:
{y:1,label:'Adnim'},
{y:2,label:'Adnim2'},
实施例:2
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},//Value of y:0 is all are zero
{y:0,label:'Adnim2'},
{y:0,label:'Adnim2'},
{y:1,label:'Adnim2'},
{y:1,label:'Adnim2'},
当前输出:
{y:2,label:'Adnim2'},
预期产出:
{y:0,label:'Adnim'},
{y:2,label:'Adnim2'},
Javscript:
var list = [
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:0,label:'Adnim'},
{y:1,label:'Adnim'},
{y:0,label:'Adnim2'},
{y:0,label:'Adnim2'},
{y:1,label:'Adnim2'},
{y:1,label:'Adnim2'},
]
var counters = {}
var result = [];
var resultString = '';
var label;
list.forEach(function(el){
label = el.label;
// Skip zero y's
if (el.y === 0) return;
// Increase counter values
if (counters.hasOwnProperty(label)) {
counters[label] += 1;
} else {
counters[label] = 1;
}
});
// Convert counters object to array of objects
for (var label in counters) {
result.push({'label': label, 'y': counters[label]});
}
// Render result to the target div
console.log(result);
result = result.map(function(el){ return '{y: ' + el.y + ', label: "' + el.label + '"}' });
resultString = '[' + result.join(', ') + ']';
$('#target').html(resultString);
答案 0 :(得分:1)
如果没有y == 0的项目,则永远不会创建计数器条目。请尝试以下替换forEach功能(在Chrome中测试):
list.forEach(function(el) {
label = el.label;
// Init the counters entry if necessary
if (!counters.hasOwnProperty(label))
counters[label] = 0;
if (el.y !== 0)
counters[label] += 1;
});