如何计算数组中字符串的数量

时间:2018-02-19 06:34:25

标签: javascript angular typescript typescript2.0

[
    {
        "assetNo":"51GQA21AP001"
    },
    {
        "assetNo":"51GQA22AP001"
    },
    {
        "assetNo":"51GQA24AP001"
    },
     {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA21AP001"
    },
     {
        "assetNo":"51GQA23AP001"
    },
    {
        "assetNo":"51GQA24AP001"
    }
]

我需要以下输出:

[{
  "assetNo": "51GQA21AP001",
  "count": 2
}, {
  "assetNo": "51GQA22AP001",
  "count": 2
}, , {
  "assetNo": "51GQA23AP001",
  "count": 2
},{
  "assetNo": "51GQA24AP001",
  "count": 1
}]

2 个答案:

答案 0 :(得分:1)

在这里:



var data = [
    {
        "assetNo":"51GQA21AP001"
    },
    {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA24AP001"
    },
     {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA21AP001"
    },
     {
        "assetNo":"51GQA23AP001"
    },
     {
        "assetNo":"51GQA24AP001"
    }
]


let count = {};
data.forEach(el => {
    count[el.assetNo] = count[el.assetNo] ? count[el.assetNo]+1 : 1; 
})

let lastResult = [];
for (var key in count) {
  lastResult.push({ assetNo : key , count : count[key] });
}

console.log(lastResult);




答案 1 :(得分:1)

您可以使用array#reduce根据assetNo对数组进行分组。



var data = [{ "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA24AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA23AP001" }, { "assetNo": "51GQA24AP001" } ],
  result = Object.values(data.reduce((r,o) => {
    r[o.assetNo] = r[o.assetNo] || {assetNo : o.assetNo, count : 0};
    r[o.assetNo].count += 1;
    return r;
  },{}));
console.log(result);