Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
•2 min read•View as Markdown
Array Flatten in JavaScript
S
I'm a full-stack developer passionate about building scalable, real-world applications from the ground up. My expertise spans the entire web development stack, from crafting semantic HTML and responsive layouts with modern CSS (Flexbox, Grid, Tailwind) to building dynamic interfaces with React, TypeScript, and Next.js.

What are nested arrays?

A nested array in JavaScript is an array that contains other arrays as its elements. In the array, the "slots" contain references to other arrays rather than just holding strings or numbers. It is also known as a 2D array or multidimensional array.

//Example of nested array
const nestedArray = [1, 2 [3, 4],[5,[6,7]]

Why is flattening arrays useful?

Flattening is the process of converting a multidimensional array into a single-dimensional array that contains all the elements. This process is useful because:

  • Data Normalization: APIs frequently return deeply nested JSON structures. Flattening this data simplifies the process of mapping or filtering it.

  • Searchability: It's much easier to perform find() on a flat list than to write complex recursive search logic for nested structures.

  • UI Rendering: Frameworks like React prefer a flat list of items for mapping into components.

Concept of flattening arrays

The objective is to flatten arrays by unwrapping all internal arrays until only non-array elements remain.

Step-by-Step Logic:

  1. Iterate through each element of the main array.

  2. Check: Is the current element an array?

  3. If No: Push it directly to our "result" list.

  4. If Yes: Go "inside" that array and repeat the process (Recursion).

Different approaches to flatten arrays

The Modern Way: Array.prototype.flat()

In modern JavaScript (ES2019+), you can use a built-in method that takes a "depth" argument.

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

console.log(nested.flat(1)); // [1, 2, [3, 4]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]

The Recursive Approach (Interview Classic)

Interviews often prohibit the use of external help. You must demonstrate problem-solving skills by writing a recursive function.

// interview asked question
function flatten(arr) {
  let result = [];
  
  arr.forEach(element => {
    if (Array.isArray(element)) {
      // If it's an array, spread the flattened result of that sub-array
      result.push(...flatten(element));
    } else {
      // If it's a value, just push it
      result.push(element);
    }
  });
  
  return result;
}

Using reduce()

A more concise and elegant approach to functional programming.

const flatten = (arr) => arr.reduce((acc, val) => 
  Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []
);