【问题标题】:How to filter and count items in Typescript from an Array如何从数组中过滤和计算 Typescript 中的项目
【发布时间】:2019-12-01 11:07:11
【问题描述】:

我想从一个数组中过滤和计算 Typescript 中的项目。

我尝试了下面给出这个结果的代码:AA,BB,AA,CC

const types = cars.map((car) => car.type);   

const cars = [
        {
            id: 2,
            brand: "Opel",
            type: "AA",
        },
        {
            id: 8,
            brand: "Toyota",
            type: "BB",
        },
        {
            id: 40,
            brand: "Opel",
            type: "AA",
        },
        {
            id: 66,
            brand: "BMW",
            type: "CC",
        }
    ];

我想按如下所示的 type 计数和排序,我该如何在 Typescript 中做到这一点?

2AA、1BB、1CC

【问题讨论】:

标签: angularjs typescript


【解决方案1】:

通过使用lodash

var result = _.countBy(cars, 'type');

输出:

{
'AA': 2
'BB': 1
'CC': 1
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2014-11-23
    • 2015-07-06
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多