Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular split list

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.

like image 662
Sox - Avatar asked Mar 30 '26 18:03

Sox -


1 Answers

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.

like image 195
p.s.w.g Avatar answered Apr 02 '26 13:04

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!