October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Flatten an Array of Arrays in TypeScript

Call .flat() for one level, pass a depth or Infinity for more, and use flatMap to map and flatten together. Here is how, plus the ES2019 lib setting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call .flat() on the array. For a two-dimensional array it returns a new, one-level array and leaves the original untouched.

const nested = [[1, 2], [3, 4]];
const flat = nested.flat(); // number[]: [1, 2, 3, 4]

That covers most cases. The rest of this article covers deeper nesting, combining a transform with flattening, the TypeScript setting that makes flat compile, and a fallback for runtimes that lack it.

As an Amazon Associate I earn from qualifying purchases.

Choose the method by the job

Need Example Result
Flatten an array of arrays one level nested.flat() Inner elements are joined into one new array.
Flatten a known deeper structure nested.flat(2) Two levels are flattened; deeper arrays may remain.
Flatten arbitrary array nesting nested.flat(Infinity) Recursively flattens every array level.
Transform each element into zero or more values, then flatten one level items.flatMap(item => makeValues(item)) Arrays returned by the callback are joined one level.

Flattening deeper than one level

The default depth is 1. MDN describes flat() as creating a new array with all sub-array elements concatenated into it recursively up to the specified depth. So with three levels, the default leaves arrays behind:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const deep = [1, [2, [3, [4]]]];

deep.flat();         // [1, 2, [3, [4]]]
deep.flat(2);        // [1, 2, 3, [4]]
deep.flat(Infinity); // [1, 2, 3, 4]

If you know the depth, prefer a finite number. It preserves any deeper arrays that are meant to be data. Use Infinity only when every array level should disappear.

Transforming and flattening: flatMap

flatMap is equivalent to map followed by flat(1). It suits cases where each item produces zero, one or several outputs:

const orders = [
  { id: 1, items: ['pen', 'ink'] },
  { id: 2, items: [] },
  { id: 3, items: ['pad'] },
];

const allItems = orders.flatMap(order => order.items);
// string[]: ['pen', 'ink', 'pad']

It flattens only one level. It is not a deep-flatten method. If your callback returns deeper nesting, chain .flat(n) afterwards.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Make TypeScript accept flat and flatMap

If the compiler reports that flat or flatMap does not exist on the array type, the cause is usually the lib option. TypeScript’s TSConfig reference for lib lists array.flat and array.flatMap under ES2019. Include ES2019 or a newer library:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
{
  "compilerOptions": {
    "target": "ES2019",
    "lib": ["ES2019"]
  }
}

In a browser project, add "DOM" to lib as well, because setting lib replaces the defaults. Alternatively, a newer target such as ES2022 pulls in the matching default libraries when lib is omitted.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Types are not runtime support

The lib setting only tells the type checker which APIs exist. TypeScript’s documentation says these declarations describe the environment, including APIs supplied by polyfills. A clean type check therefore does not add flat() to an older runtime. Check the engines you actually deploy to, or load a polyfill. No version-by-version support table is given here, so verify against your own targets.

One-level fallback without native flat

A reducer with concat is a common substitute for the one-level case. It is a suggested pattern, not something tested in a specific environment:

const flat = nested.reduce<number[]>(
  (result, part) => result.concat(part),
  []
);

Replace number with the element type of your data.

Behavior to know about

  • No mutation. flat() returns a new array; the source is unchanged. The inner arrays are not copied deeply, though, so objects inside are the same references.
  • Sparse slots are dropped. Empty slots at the root and in the levels being flattened are omitted from the result.
  • Mixed content is allowed. Non-array elements stay as they are. In a mixed array like [1, [2]], the result is a union-typed array, here number[].
  • Only arrays are flattened. Other iterables, such as Set, are not expanded. Convert them first, for example with Array.from.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.