【问题标题】:Remove Duplicate and show Unique With Count in Div删除重复项并在 Div 中显示具有计数的唯一性
【发布时间】:2015-06-06 22:29:15
【问题描述】:

我想根据标签“a”计算“0”的总数,并根据标签“a”计算“1”的总数。并根据标签“b”计算“1”的总数。

Div:输入1

[   
    {y: 0 ,  label: 'a'}, 
    {y: 0 ,  label: 'a'}, 
    {y: 1 ,  label: 'a'}, 
    {y: 1 ,  label: 'a'}, 
    {y: 1, label: 'b'}, 
    {y: 1, label: 'b'}, 
    {y: 1, label: 'b'}

]

Div:输入2

[   
    {y: 0 ,  label: 'a'}, 
    {y: 0 ,  label: 'a'}, 
    {y: 1 ,  label: 'a'}, 
    {y: 1 ,  label: 'a'}, 
    {y: 1, label: 'b'}, 
    {y: 1, label: 'b'}, 
    {y: 1, label: 'b'}

]

我想要输出,删除重复项” 我期望的关于输入的输出是:

Div output1:这将只计算 div input1 的“1”

[   
        {y: 2,  label: 'a'},
        {y: 3,  label: 'b'}, 

    ]

Div output2:这将只计算 div input2 的“0”

[   
        {y: 2,  label: 'a'},
        {y: 0,  label: 'b'}, 

    ]

【问题讨论】:

  • 您的问题令人困惑!请改写你的问题!
  • @Tim 我已经修改了我的问题以便更好地理解。请告诉我你的建议
  • @Tim 等待回复....
  • 如果您不明白,或者需要 mroe cmets,请告诉我! :)

标签: javascript html


【解决方案1】:

是的,有可能!

这个问题被称为聚合问题,通常你会使用map和reduce来聚合值

//data is the your value array
data.filter(function(item) {
    //filter the data with the condition
    return !((item.y === 1) && (item.label === 'a'));
}).reduce(function(result, value) {
    let label = value.label;

    //Check if the label exists?, if yes, add the y value
    for (let i = 0; i < result.length; i++) {
        if(result[i].label === label) {
            result[i].y++;

            return result;
        }
    }

    //If label not exist add new label into the array and init the y value
    result.push({
        label: label,
        y: 1
    })

    return result;
}, []); // Init an empty array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2021-05-31
    • 1970-01-01
    • 2017-01-15
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多