惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
博客园 - 【当耐特】
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
雷峰网
雷峰网
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
博客园 - 叶小钗
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
B
Blog RSS Feed
H
Help Net Security
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
L
LangChain Blog
Vercel News
Vercel News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Mastering Array Flattening in JavaScript: From Nested Cha...
Ritam Saha · 2026-04-27 · via DEV Community

Imagine you're building a shopping cart app. Users add items like ["apple", "banana", ["orange", ["grape", "kiwi"]]]. Suddenly, your loops break because of those sneaky nested arrays. Frustrating, right?
Array flattening turns this mess into a simple ["apple", "banana", "orange", "grape", "kiwi"]. In this blog, we'll demystify nested arrays, explore why flattening matters, break down approaches step-by-step, and tackle real interview scenarios—including a custom polyfill you can steal (or improve).


What Are Nested Arrays?

Nested arrays are arrays containing other arrays as elements within it.

Original Nested Array:
[
  1,
  [2, 3],
  [4, [5, 6], 7],
  8
]

Enter fullscreen mode Exit fullscreen mode

Think of it like a filing cabinet: top-level folders hold documents and sub-folders.


Why Flatten Arrays win in Real-world scenarios?

Flattening simplifies data for:

  • Iteration: Loop once without if (Array.isArray(item)) checks.
  • Processing: Easier sorting, filtering, or mapping on flat lists.
  • UI Rendering: Display cart items or file trees linearly.
  • Performance: Reduces recursion depth in algorithms.

Example: Flattening [1, [2,3], 4] will let array.map(x => x*2) over the flatten array yield [2,4,6,8] cleanly.


The Flattening Concept: Step-by-Step

Flattening extracts all elements into a single-level array. Key decisions:

  1. Copy: Shallow vs. deep
  2. Depth control: Stop at a max depth to avoid infinite nests.
  3. Preserve order: Process left-to-right.
Step 1: Start with [1, [2,3], [4, [5,6], 7], 8]
Step 2: Extract 1 → result: [1]
Step 3: Dive into [2,3] → extract 2,3 → result: [1,2,3]
Step 4: Dive into [4, [5,6], 7] → extract 4, dive deeper to 5,6 → extract 7 → result: [1,2,3,4,5,6,7]
Step 5: Extract 8 → result: [1,2,3,4,5,6,7,8]

Enter fullscreen mode Exit fullscreen mode

Flattening step-by-step


Different Approaches to Flatten Arrays

Native flat(depth) (ES2019+)

Simplest: Going to flat the given array upto the specified depth. depth means upto which level it's going to be spread. arr.flat(Infinity) handles any depth.

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

Enter fullscreen mode Exit fullscreen mode

Pros: Built-in, readable. Cons: Browser support (IE doesn't support).

Iterative with reduce + concat

No recursion—great for huge arrays.

function flatten(arr) {
  return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(...val) : acc.concat(val), []);
}

Enter fullscreen mode Exit fullscreen mode

Step-by-step: Accumulator starts empty, concat spreads nested arrays and adds them after spreading, otherwise simple add.

Recursive Custom (Polyfill Style)

Dive deep with a helper function—scales to any depth. We going to discuss about this in the next section.


Common Interview Scenarios

Interviewers love asking: "Implement Array.prototype.flat polyfill!" or "Flatten without natives, handle depth."

Building your own Polyfill: A Strong Solution

Here's your code—clean and correct:

Array.prototype.myFlat = function(depth = 1) {
    const result = [];
    const flatten = function(arr, depth) {
        for(let i = 0; i < arr.length; i++) {
            if(Array.isArray(arr[i]) && depth > 0) {
                flatten(arr[i], depth - 1);
            } else {
                result.push(arr[i]);
            }
        }
    }
    flatten(this, depth);
    return result;
}

console.log([1,2,3,4,5,[6,7,8,[9,10]]].myFlat(Infinity)); // [1,2,3,4,5,6,7,8,9,10]

Enter fullscreen mode Exit fullscreen mode

Understanding polyfill code

Analysis (Problem-Solving Thinking):

  • In this polyfill, an empty array been taken called as result.
  • It uses a helper function, that iterate over every element of the array.
  • If it's an simple value then directly push to the result array.
  • If the element is an array and the depth is greater than 0, then it will call the same helper fucntion using the element which is actually an array with depth-1
  • after the all the nested array been spread (if depth=Infinity) or if the depth becomes 0, then it will stop and return the result array.

Note: I would recommend a dry run by your own. take a pen-paper and try dry-run

Interview Tip: Explain trade-offs: Recursion shines for trees; iteration for 1M+ elements. Here time-complexity: O(n) time (visits each element once) and O(depth) stack space.


Flattening isn't just a trick—it's a mindset for taming messy data. Practice these, tweak your polyfill and you'll crush interviews. Next time you hit nested chaos, myFlat(Infinity) has your back.