Skip to main content

Command Palette

Search for a command to run...

JavaScript mein Array Flattening

Updated
5 min readView as Markdown

Modern JavaScript apps mein aksar aisa hota hai ki API, forms, ya UI components se aane wale data nested arrays ke form mein hote hain, jaise:

const nested = [1,, [4, ]];[1][2][3][4]

Aur humein chahiye:

[2][3][4][5][6][1]

Is process ko Array Flattening bolte hain. Aaj dekhte hain ki JavaScript mein hum array flattening kaise karte hain, kyu karte hain, aur real‑world code kaise likhte hain.


1. Array.flat() – Modern JS ka shortcut

JavaScript (ES2019+) ne ek built‑in method diya: flat().

const nested = [1,, [4, ]];[3][4][1][2]

console.log(nested.flat());         // 1 level flat → [1, 2, 3, 4, ][4][3]
console.log(nested.flat(Infinity)); // pure flat →[5][6][1][2][3][4]

Kya hota hai?

  • flat() sirf pehle level ko flatten karta hai.

  • flat(Infinity) depth‑agnostic hai, saari nesting “khol” deta hai.

Kab use karein?

  • Agar tum modern browsers / Node.js use kar rahe ho → flat(Infinity) best choice hai (clean, readable, efficient).

2. reduce() + concat() – Functional style

Agar flat() available nahi ho (old browser / polyfill), to classic approach:

const arr = [,, ];[6][1][2][3][4][5]

const flat = arr.reduce((acc, curr) => acc.concat(curr), []);
console.log(flat); //[1][2][3][4][5][6]

Logic:

  • acc initially empty array.

  • Har curr ko concat karke ek single flat array banata hai.

Ye functional programming‑style method interviews mein bhi pasand kiya jata hai.


3. Recursion se full flatten (any depth)

Agar arrays bahut deep ho, jaise tree‑like structure:

const deep = [1, [2, ], ];[2][3][4][6]

To recursion‑based logic:

function flatten(arr) {
  const result = [];
  for (let item of arr) {
    if (Array.isArray(item)) {
      result.push(...flatten(item)); // recursive call
    } else {
      result.push(item);
    }
  }
  return result;
}

console.log(flatten(deep)); //[3][4][5][6][1][2]

Advantage:

  • Tumhare control me complete logic.

  • Saari depth handle kar sakta hai.

  • Interview mein recursion + Array.isArray() dono concepts clearly show hote hain.


4. Spread + concat() – 2D arrays ke liye

2D arrays ke liye chhota, elegant tareeka:

const arr = [, ];[5][6][1][2]

const flat = [].concat(...arr);
console.log(flat); //[6][1][2][5]

...arr se har sub‑array unpack hota hai aur concat unko ek single array me jod deta hai. Ye pattern 2D arrays ke liye perfect hai, depth‑zada ke liye flat() ya recursion better hai.


5. Real‑world use cases

Real apps mein array flattening sirf theory nahi; practical utility hai. Neeche kuch examples:

API responses

Backend groups ke form me permission ya tags bhejta hai:

const response = {
  userId: 101,
  permissions: [
    ["read", "write"],
    ["delete"],
    ["share", ["download", "upload"]]
  ]
};

const allPermissions = response.permissions.flat(Infinity);
console.log(allPermissions);
// ["read", "write", "delete", "share", "download", "upload"]

Flattened data ko access checks, UI badges, ya feature toggles me directly use kar sakte ho.

Tags / categories

Product, blog, ya search systems me tags groups ke form me aate hain:

const productResponse = {
  id: 1,
  name: "Laptop",
  tags: [["electronics", "computer"], ["office"], ["premium", "tech"]]
};

const flatTags = productResponse.tags.flat();
console.log(flatTags);
// ["electronics", "computer", "office", "premium", "tech"]

Flattening se filtering, search, ya tag chips simple ho jate hain.

Forms

Multi‑step ya grouped selections ka example:

const formData = {
  sections: [
    ["HTML", "CSS"],
    ["JavaScript"],
    ["React", "Node.js"]
  ]
};

const selectedSkills = formData.sections.flat();
console.log(selectedSkills);
// ["HTML", "CSS", "JavaScript", "React", "Node.js"]

Ye pattern multi‑step forms, checkbox groups, ya survey UIs me kaafi useful hai.

Nested comments / tree data

Har jagah flat() kaam nahi karta, especially nested objects ke case me:

const comments = [
  {
    id: 1,
    text: "Nice post",
    replies: [
      { id: 2, text: "Thanks!" },
      {
        id: 3,
        text: "Very helpful",
        replies: [{ id: 4, text: "Glad it helped" }]
      }
    ]
  }
];

function flattenComments(comments) {
  const result = [];

  for (const comment of comments) {
    result.push({ id: comment.id, text: comment.text });

    if (comment.replies) {
      result.push(...flattenComments(comments));
    }
  }

  return result;
}

console.log(flattenComments(comments));

Ye pattern threaded comments, nested menus, ya tree views me kaam aata hai.

Reusable utility function

Agar flattening logic baar‑baar aata hai, to ise ek utility function me rakhna better hai:

function flattenArray(arr) {
  return arr.flat(Infinity); // modern
}

// ya legacy‑safe version:
function flattenArrayLegacy(arr) {
  return arr.reduce((acc, item) =>
    Array.isArray(item)
      ? acc.concat(flattenArrayLegacy(item))
      : acc.concat(item)
  , []);
}

6. Kaunsa method choose karein?

Method Best use case Pro / Con
flat() / flat(∞) Modern code, quick solution Clean, native, readable
reduce + concat() Functional / interview code Flexible, readable, recursion nahi handle
Recursion loop Deep nesting, any depth Full control, thoda lengthy
Spread + concat() Simple 2D arrays Very short, depth‑limited

7. Final tips

  • Production code:

    • Browser support hai → flat(Infinity) prefer karo.

    • Legacy support chahiye → recursion / reduce wala utility function use karo.

  • Interviews:

    • Pehle flat() se start karo, phir recursion / reduce se logic bhi dikhao.

More from this blog