如何计算重复项目的计数以及那里的状态

How to calculate count for duplicated Item along with there status

本文关键字:状态 那里 项目 何计算 计算      更新时间:2023-09-26
_dataDetails = {
    name : test1 ,
    status : found,
    other : []
}
{
    name : test1 ,
    status : found,
    other : []
}
{
    name : test1 ,
    status : Not found,
    other : []
}
{
    name : test2 ,
    status : found,
    other : []
}etc ........

我想计算每个名字的已找到和未找到的计数。

For example:
test1 
found:2
notfound :1
test2 
found:1
notfound :0

可以编码

var _data = []
var index = -1;
for ( var _i = 0; _i < _data.length; _i++ )
{
    if ( _data[_i][0] == _dataDetails[i].name ) { index = _i; }
}

if ( index >= 0 )
{
    if ( _dataDetails[i].status == 'found' )
    {
        _data[index][1][0]++;
    }
    else
    {
        _data[index][1][1]++;
    }
}
else
{
    if ( _dataDetails[i].result == 'Detected' )
    {
        _data.push([_dataDetails[i].name, [1, 0]]);
    }
    else
    {
        _data.push([_dataDetails[i].name, [0, 1]]);
    }
}

这里我得到双倍计数(而不是10,它将给出20)。请建议。

你可以这样编码

var _dataDetails = [{
    name : test1 ,
    status : found,
    other : []
}
{
    name : test1 ,
    status : found,
    other : []
}
{
    name : test1 ,
    status : Not found,
    other : []
}
{
    name : test2 ,
    status : found,
    other : []
}];
var counter = {};
for(index in _dataDetails) {
    var dt = _dataDetails[index];
    if(counter[dt.name]) {
        counter[dt.name] += 1;
    } else {
        counter[dt.name] = 1;
    }
}
console.log(counter);

你可以这样做。

    _dataDetails = [{
        name : "test1" ,
        status : "found",
        other : []
    },
    {
        name : "test1" ,
        status : "found",
        other : []
    },
    {
        name : "test1" ,
        status : "Not found" ,
        other : []
    },
    {
        name :"test2" ,
        status : "found",
        other : []
    }]
    var results={};
    _dataDetails.forEach ( function (o,i) {
        if(!results[o.name]) { 
    results[o.name] = {} ;
    results[o.name].found = 0;
    results[o.name].notfound = 0;
    }
        if (o.status === "found" ) {
    results[o.name].found++}
       else if (o.status === "Not found" ) {results[o.name].notfound++}
    });
    Object.getOwnPropertyNames(results).forEach(function(prop) {
    console.log( prop + "  found : " + results[prop].found + " ,  not found: "+ results[prop].notfound);
    });

请看这里:http://jsbin.com/kavesu/edit?js,console