简体   繁体   中英

How to count elements from nested arrays (3 level) in TypeScript?

export interface Cars {
    items: ItemsSummary[];
}

export interface ItemsSummary{
    details: DetailsSummary[];
}

export interface DetailsSummary{
    name: string;
}

I have 3 level nested array. I want to get know how many Details belongs to Car Something like this: cars.flat(t=>t.items).flat(t=>t.details).length

Use reduce :

let totalDetails = cars.reduce((total, car) => {
    return total += car.items.reduce((total2, item) => {
        return total2 += item.details.length;
    }, 0);
}, 0);

您可以使用reduce来总结长度:

cars.reduce((s, o) => s + o.items.reduce((ss, oo)=> ss+ oo.details.length, 0), 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM