Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
2 min read

What are Nested Arrays?

  • A nested array is simply an array that contains other arrays as its elements

  • This is also called as a multi-dimensional array

Example:

const messyData = [1, [2, 3], [[4, 5], 6]]

Here messyData has 3 levels of depth, its like having a box that contains smaller box, than contains even smaller box

The concept of flattening

Flattening is the process of converting a multi-dimensional array into a single level array. You ‘extract’ every individual value from its sub-container and place it into one continuous list

const res = [1, 2, 3, 4, 5, 6]

Why flattening is useful

  • Data Consistency: API’s often return deeply nested JSON. Flattening makes it easier to map or filter the data for your UI components (like the userProfile or orderProcessing modules in your diagram)

  • Simplifying Logic: It’s much easier to run a single forEach or find on a flat list than it is to write complex recursive loops to search through layers of nested arrays

  • Performance: Searching a flat array is generally faster and less memory-intensive than traversing a deep tree structure.

Different approaches to flattening

  • The modern way (flat)

    • Javascript now has a built-in method that does this in one line
const nested = [1, [2, [3]]];
console.log(nested.flat(2)) // Result: [1,2,3], here 2 is depth
  • The Recursive Way (Classic interview question)

    • If you do not know the depth, you use a function that calls itself until it hits a non array value
function flatten(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
  • The spread operator hack

    • For arrays that are only one level deep
const flat = [].concat(...[1, [2, 3], [4]]);
Pasted Graphic 1.tiff

Common Interview Scenarios

  • Flatten to a specific depth: You might be asked to only flatten the first two layers of a five-layer array

  • Flatten without built-ins: Interviewers ofter ban .flat() to see if you understood recursion or how to use .reduce()

  • Performance optimisation: You might be asked how to flatten a massive array without causing a stack-overflow error