首页 > 解决方案 > 如何从数组中过滤和计算 Typescript 中的项目

问题描述

我想从数组中过滤和计算 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",
        }
    ];

我想像下面这样按类型计数和排序,我该如何在 Typescript 中做到这一点?

2AA、1BB、1CC

标签: angularjstypescript

解决方案


通过使用lodash

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

输出:

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

推荐阅读