展平数组的数组并与打字稿中的另一个数组组合

时间:2019-01-02 18:13:42

标签: arrays typescript

根据this文章,您可以使用concat展平数组。

例如;

const nestedArrays: Person[][] = [
    [
        {firstName: "Andrew", lastName: "Smith"},

    ],
    [
        {firstName: "Chris", lastName: "Cawlins"},
    ],
    [
        {firstName: "Susan", lastName: "Sarandon"},
    ]
]

将被转换为

const flattenedArray: Person[] = [
    {firstName: "Andrew", lastName: "Smith"},
    {firstName: "Chris", lastName: "Cawlins"},
    {firstName: "Susan", lastName: "Sarandon"},
]

使用

const flattenedArray = [].concat(...nestedArrays);

我还有一个额外的数组,如下所示,

const additional = ["extra1", "extra2"];

我的最终结果应该是

[
 ["extra1", "extra2"],
 [{firstName: "Andrew", lastName: "Smith"}],
 [{firstName: "Chris", lastName: "Cawlins"}],
 [{firstName: "Susan", lastName: "Sarandon"}],
]

我可以在打字稿中使用concat来实现吗?还是我会使用另一种方法?

1 个答案:

答案 0 :(得分:0)

您不必压平任何东西,只需使用unshift进行前缀:

const nestedArrays: Person[][] = [
    [
        {firstName: "Andrew", lastName: "Smith"},

    ],
    [
        {firstName: "Chris", lastName: "Cawlins"},
    ],
    [
        {firstName: "Susan", lastName: "Sarandon"},
    ]
]
const additional = ["extra1", "extra2"];
const combination = nestedArrays.unshift(additional);