Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Turn complex nested arrays into a simple, flat structure

Updated
6 min read
Array Flatten in JavaScript
A

Hi, I’m Abdul Samad. A web development learner and tech enthusiast. I write about what I learn, share practical coding tips, and publish in-depth blogs on programming and modern web development.

Check out my full collection of blogs on Hashnode: https://abdulsamad30.hashnode.dev/

Connect with me on X for quick updates and insights: @abdul_sama60108

You've got an array. Inside it? More arrays. And inside those? Even more arrays. It's arrays all the way down, and you just need a simple, clean list. Welcome to array flattening.

What Are Nested Arrays?

A nested array is an array that contains other arrays as its elements. Instead of just holding simple values like numbers or strings, it holds entire arrays within itself.

const simpleArray = [1, 2, 3, 4];
const nestedArray = [1, [2, 3], 4, [5, [6, 7]]];

In the nested array above, we've got numbers mixed with arrays, and some of those arrays contain more arrays.

Real-life analogy: Your computer's file system. You have folders, and inside those folders are more folders, and eventually you get to the actual files.

A nested array is the same structure containers inside containers.

Why Flattening Arrays Is Useful

Flattening transforms nested arrays into a single-level array. You take all those inner arrays and pull their elements out into one continuous list.

When you need it:

  • Processing data from APIs that return nested structures

  • Cleaning up recursive operations that build up layers

  • Preparing data for operations that expect flat arrays (sorting, filtering, etc.)

  • Interview questions (because they love asking about it)

Real-life analogy: You're creating a group chat with friends. Some people are already in smaller group chats together. Instead of inviting entire groups (which creates nested groups), you want to flatten it - just invite each individual person to one main chat.

const friendGroups = [
  ['Alice', 'Bob'],
  'Charlie',
  ['Diana', ['Eve', 'Frank']]
];

// Hard to work with. How many people total? Can't easily message everyone.

The Concept of Flattening Arrays

Flattening means taking all nested elements and bringing them up to the top level. There are different depths you might want to flatten:

Shallow flattening: Only removes one level of nesting Deep flattening: Removes all levels, no matter how deep

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

// Shallow flatten: [1, 2, [3, [4]]]
// Deep flatten: [1, 2, 3, 4]

Real-life analogy: Think about finding all the music files on your computer. Shallow flattening is like opening your "Music" folder and seeing what's immediately inside some songs and some subfolders.

Deep flattening is like searching your entire Music folder and getting every single song file, no matter how buried it is in subfolders.

Different Approaches to Flatten Arrays

1. Using flat() (Modern JavaScript)

The simplest way. The flat() method is built into JavaScript arrays.

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

// Flatten one level
const shallowFlat = nested.flat();
console.log(shallowFlat);
// Output: [1, 2, 3, 4, [5, 6]]

// Flatten all levels
const deepFlat = nested.flat(Infinity);
console.log(deepFlat);
// Output: [1, 2, 3, 4, 5, 6]

// Flatten exactly 2 levels
const twoLevels = nested.flat(2);
console.log(twoLevels);
// Output: [1, 2, 3, 4, 5, 6]

When to use: Modern projects, ES2019+. It's clean, readable, and does exactly what you need.

2. Using reduce() and concat()

Before flat() existed, this was the go-to approach for shallow flattening.

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

const flattened = nested.reduce((acc, current) => {
  return acc.concat(current);
}, []);

console.log(flattened);
// Output: [1, 2, 3, 4, 5, 6]

How it works: reduce() iterates through the array. For each element, it concatenates it with the accumulator. If the element is an array, concat() spreads it out.

When to use: When you need control over the flattening logic or are working in older environments without flat().

3. Recursive Approach (Deep Flattening)

For complete control over deep flattening, recursion is your friend.

function flattenDeep(arr) {
  return arr.reduce((acc, current) => {
    if (Array.isArray(current)) {
      return acc.concat(flattenDeep(current));
    }
    return acc.concat(current);
  }, []);
}

const deepNested = [1, [2, [3, [4, [5]]]]];
console.log(flattenDeep(deepNested));
// Output: [1, 2, 3, 4, 5]

How it works: Check each element. If it's an array, recursively flatten it. If not, add it to the result. Keep going until you hit the bottom.

Real-life analogy: Searching for a specific file on your computer. You open a folder. If it contains more folders, you open those too. You keep drilling down until you find actual files, not more folders.

4. Using Spread Operator (Shallow Only)

Quick one-liner for shallow flattening.

const nested = [1, [2, 3], [4, 5]];
const flattened = [].concat(...nested);

console.log(flattened);
// Output: [1, 2, 3, 4, 5]

When to use: When you know you only need one level removed and want minimal code.

5. The toString() Hack (Numbers Only)

A clever trick that only works for arrays of numbers.

const nested = [1, [2, [3, [4]]]];
const flattened = nested.toString().split(',').map(Number);

console.log(flattened);
// Output: [1, 2, 3, 4]

How it works: toString() on an array creates a comma-separated string of all values, regardless of nesting. Split on commas, convert back to numbers.

Warning: Only works for numbers. Strings, objects, and mixed types will break this.

Common Interview Scenarios

Scenario 1: "Flatten this array without using flat()"

This tests your understanding of iteration and recursion.

// Interview answer using reduce
function flatten(arr) {
  return arr.reduce((acc, item) => {
    return Array.isArray(item)
      ? acc.concat(flatten(item))
      : acc.concat(item);
  }, []);
}

const test = [1, [2, 3], [[4], 5]];
console.log(flatten(test));
// Output: [1, 2, 3, 4, 5]

What they're testing: Can you handle recursion? Do you understand how arrays work at a fundamental level?

Scenario 2: "Flatten only to a specific depth"

function flattenToDepth(arr, depth = 1) {
  if (depth === 0) return arr;

  return arr.reduce((acc, item) => {
    return Array.isArray(item)
      ? acc.concat(flattenToDepth(item, depth - 1))
      : acc.concat(item);
  }, []);
}

const nested = [1, [2, [3, [4]]]];
console.log(flattenToDepth(nested, 2));
// Output: [1, 2, 3, [4]]

What they're testing: Can you add parameters and control recursion depth?

Scenario 3: "Flatten and remove duplicates"

Combining flattening with Set for unique values.

const nested = [1, [2, 2], [3, [3, 4]]];
const flatUnique = [...new Set(nested.flat(Infinity))];

console.log(flatUnique);
// Output: [1, 2, 3, 4]

What they're testing: Can you chain operations and think about data transformations?

Scenario 4: "Flatten this without built-in methods"

The hardcore approach, showing you understand loops.

function flattenManual(arr) {
  const result = [];
  const stack = [...arr];

  while (stack.length) {
    const item = stack.pop();

    if (Array.isArray(item)) {
      stack.push(...item);
    } else {
      result.unshift(item);
    }
  }

  return result;
}

const nested = [1, [2, [3, 4]]];
console.log(flattenManual(nested));
// Output: [1, 2, 3, 4]

How it works: Use a stack to track items. Pop an item. If it's an array, push its contents back onto the stack. If not, add it to results. Keep going until the stack is empty.

What they're testing: Can you solve problems with basic data structures when you can't reach for helper methods?


Wrapping Up

Array flattening is one of those operations that looks simple but has depth (pun intended). You've got modern solutions like flat() for everyday work, and manual approaches for when you need control or are stuck in an interview.

FIN ✌️