[RECIPE]: array flatten and distinct in TS

[RECIPE]: array flatten and distinct in TS

I caught up myself on a thought that I have looked to a way to flatten array in TS several times this year. Probably, I had bad memory and cannot remember this easily. But maybe, it's more because this is not something you do everyday. So, let's keep the recipe here

Use case: you have array of arrays of similar elements, which you want to flatten. As simple as that:

const data: ItemType[] = [{id: 1, items: [...]}, {id: 2, items: [...]}];
const flattenElements: ItemType[] = ([] as ItemType[]).concat(
        ...data.map(x => x.items),
    );

The key thing - usage of concat function. But with couple of tricks:

  • Concat function is not type safe (or better to say, [] doesn't have type), so use `as` keyword with your type for initial value: `[] as ItemType[]`
  • Inside concat callback it is necessary to use `...` operator, so that your array will be re-build and concat can work with all items. Otherwise - concat will simply push your array as another single element of result array

Keep calm and do smart things!