0

According to this article you can flatten an array using concat.

For example;

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

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

will can be converted to

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

by using

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

I have an additional array like the follows,

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

My end result should be

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

Can I achieve that using concat in typescript? Or is there another method that I would be using?

5
  • Possible duplicate of merge two object arrays with Angular 2 and TypeScript? Commented Jan 2, 2019 at 18:24
  • The difference is if I use additional.concat(nestedArray), it would end up in something like ["extra1", "extra2", <rest of the things>] which I do not want in this case Commented Jan 2, 2019 at 18:31
  • 1
    How about if you define const additional = [["extra1", "extra2"]]; Commented Jan 2, 2019 at 18:33
  • 2
    The result is still array of arrays, so I don't see a reason for flattening. const flattenedArray = [additional].concat(nestedArrays); Commented Jan 2, 2019 at 18:34
  • Both the above suggestions work const additional = [["extra1", "extra2"]]; and const flattenedArray = [additional].concat(nestedArrays); Commented Jan 2, 2019 at 19:08

1 Answer 1

0

You dont have to flatten anything just use unshift to prepend:

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

    ],
    [
        {firstName: "Chris", lastName: "Cawlins"},
    ],
    [
        {firstName: "Susan", lastName: "Sarandon"},
    ]
]
const additional = ["extra1", "extra2"];
const combination = nestedArrays.unshift(additional);
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking the same, but that would probably result in TypeScript compilation error because the additional array is not Person type. It will probably have to be changed to any[][] type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.