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

时间:2015-07-17 09:14:50

标签: javascript jquery

_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)。请建议。

2 个答案:

答案 0 :(得分:2)

你可以像这样编码

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

答案 1 :(得分:1)

你可以这样做。

getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

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