Skip to main content
added 412 characters in body
Source Link
Alex Hall
  • 35.8k
  • 5
  • 62
  • 94

Here's a generic solution:

function flatten<T>(arr: T[][]): T[] {
  return ([] as T[]).concat(...arr);
}

And a deep/recursive extension:

type NestedArray<T> = Array<NestedArray<T> | T>;

function flattenDeep<T>(input: NestedArray<T>): T[] {
  return flatten(input.map(x => Array.isArray(x) ? flattenDeep(x) : [x]));
};

This answer may be more efficient for a deep flatten, I just had fun trying to write something that felt more elegant to me.

Here's a generic solution:

function flatten<T>(arr: T[][]): T[] {
  return ([] as T[]).concat(...arr);
}

Here's a generic solution:

function flatten<T>(arr: T[][]): T[] {
  return ([] as T[]).concat(...arr);
}

And a deep/recursive extension:

type NestedArray<T> = Array<NestedArray<T> | T>;

function flattenDeep<T>(input: NestedArray<T>): T[] {
  return flatten(input.map(x => Array.isArray(x) ? flattenDeep(x) : [x]));
};

This answer may be more efficient for a deep flatten, I just had fun trying to write something that felt more elegant to me.

Source Link
Alex Hall
  • 35.8k
  • 5
  • 62
  • 94

Here's a generic solution:

function flatten<T>(arr: T[][]): T[] {
  return ([] as T[]).concat(...arr);
}