rotem-horovitz
    _hello_about-me_blog_snippets_projects_games
find me in:
privacy
← Back to snippets

flatten

Recursively collapse a nested array into a single flat array. A deep version of Array.prototype.flat with explicit typing.

May 20, 2026
utilityarrays

A recursive flatten that drills through arrays of any depth. The signature accepts (T | T[])[] and returns T[] — so the type system reflects the collapse.

export function flatten<T>(arr: (T | T[])[]): T[] {
	return arr.reduce<T[]>(
		(acc, item) =>
			acc.concat(Array.isArray(item) ? flatten(item as (T | T[])[]) : item),
		[],
	);
}

Compared to Array.prototype.flat

  • arr.flat(Infinity) does the same thing without the recursion, but with a wider type signature (unknown[]).
  • This version keeps element typing precise when you know the leaf type up front.