Guides

How to flatten an array — and why flat() doesn't finish the job the first time

Illustration: boxes inside boxes unpacked into one neat row

A familiar scene. You asked the AI to load products from all five catalog pages. It wrote the code, you print the count — and see 5. Not 500 products. Five.

The products didn't vanish. They're just sitting in boxes inside a box: an array of five arrays of a hundred products each. You need one flat list. That's called flattening an array. Let's go step by step, including the trap almost everyone trips over.

Step by step: from boxes to one row

  1. Look at what you actually have. Don't guess — print the first element:

    console.log(pages.length);        // 5
    console.log(Array.isArray(pages[0])); // true — arrays inside
    

    If the first element is an array, you have nesting. If it's an object, go to step 4.

  2. Remove one level of nesting — flat().

    const products = pages.flat();
    console.log(products.length); // 500
    

    That's it for the most common case. flat() takes the contents of each inner box and lays it out in one row.

  3. If there are more boxes inside — set the depth. Here's the trap: flat() with no argument removes exactly one level.

    const nested = [1, [2, [3, [4]]]];
    nested.flat();          // [1, 2, [3, [4]]] — still arrays inside!
    nested.flat(Infinity);  // [1, 2, 3, 4]
    

    The number in parentheses is how many levels to remove. Infinity means "all the way down". Use it when you don't know the depth in advance.

  4. If the arrays live inside objects — flatMap(). Typical case: you have a list of orders, and each order has a list of items. You want all items at once:

    const items = orders.flatMap((order) => order.items);
    

    flatMap is map plus flat() in one step. It pulls items out of each order, then lays everything out in one row.

  5. Don't lose where things came from. After flattening, an item no longer knows which order it belonged to. If that matters, carry the field along:

    const items = orders.flatMap((order) =>
      order.items.map((item) => ({ ...item, orderId: order.id }))
    );
    

    Now every item has an orderId. Without this step you can't later show "item from order #42".

What you get

Before: an array of five arrays, length is 5, and you can't render the products as a list.

After: one flat array of 500 products. You can filter, sort and render it as cards. And if you did step 5, every element links back to its "parent".

How to check it's fully flat

Don't trust your eyes — one nested array in the middle of a list is easy to miss. Check with one line:

console.log(products.some(Array.isArray)); // false — no arrays inside

some scans the list and answers true if even one element is an array. Got false — the data is flat, go render the cards. Got true — back to step 3 and raise the depth.

The second check is the total. If each page has a hundred products and there are five pages, you should end up with 500. Fewer — some page came back empty or with an error. More — you probably loaded one page twice.

Three gotchas nobody mentions

  • flat() drops holes. [1, , 3].flat() gives [1, 3]. If you counted positions by index, the indexes shift.
  • Strings don't get split. ["a b", "c"].flat() stays as is. To split strings into words, you need flatMap((s) => s.split(" ")).
  • The old concat trick only removes one level. The AI sometimes writes [].concat(...arr). That's the same as flat() with no argument, just less readable. It can't open deep arrays.

How to ask the AI

To avoid "5 instead of 500", describe the shape of the data right in the task:

Weak promptLoad products from all pages.
Strong promptLoad products from all 5 API pages in parallel. Each page returns an array of products. In the end I need ONE flat array of all products, not an array of arrays. Add a console.log with the final count.

Once you name the shape of the result — "one flat array" — the AI adds .flat() on its own. To see when a plain loop beats a chain of methods, check loop vs map.

What's the difference between flat and flatMap?

flat() only flattens an already nested array. flatMap() first transforms each element with a function, then flattens the result by one level.

Is flat(Infinity) dangerous?

Not for normal data. Only an array that contains itself is a problem: that code fails with "Maximum call stack size exceeded". API data never looks like that.

Does flat work in every browser?

Yes. flat and flatMap have been supported by all modern browsers and Node.js for years. No polyfills needed.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →