3

I have a list looking like so

[[{A},{B}], {C}]

Is there any simple method without having to create a function that will flatten this to an array looking like so

[{A},{B},{C}]

I searched on SO but did not find anything with typescript methods.

Thanks.

Edit : A, B and C are the same types.

devDan
  • 5,969
  • 3
  • 21
  • 40
Sox -
  • 592
  • 1
  • 9
  • 28

1 Answers1

6

It appears that what you're looking for is the built-in Array.prototype.flat:

const input = [['foo', 'bar'], 'baz'];
const output = input.flat(); // ['foo', 'bar', 'baz']

Note that you'll have to compile this with esnext support. See this question for more details. It also won't work out of the box on IE or Edge. If that's a problem in your use case, you'll want to use the polyfill that's shown in the MDN link above.

Alternatives exist in numerous libaries, for example, lodash, underscore.js, and Ramda all have an equivalent flatten method.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331