gpt4 book ai didi

javascript - 将值添加到 y :axis if all the values are Zero after filtering

转载 作者:行者123 更新时间:2023-12-03 09:55:40 25 4
gpt4 key购买 nike

有一个 JavaScript 可以删除重复的标签 label:'Adnim' 并通过跳过零“0”y 仅计数“1”y:1, :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'},

JavaScript:

 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);

最佳答案

当没有 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;
});

关于javascript - 将值添加到 y :axis if all the values are Zero after filtering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30748765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com