Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
•1 min read•View as Markdown
Array Flatten in JavaScript

What nested arrays are

Array inside array is called nested array.

Why flattening arrays is useful

One of the usecase is that we want all users post in single array to display it.

const users = [
  { name: "A", posts: ["p1", "p2"] },
  { name: "B", posts: ["p3"] }
];

const allPosts = users.map(u => u.posts).flat();

Concept of flattening arrays

One of the way to flatten the arrays is to use flat function.

flat - It takes optional depth parameter. Depth denotes how much level of depth we want array to flat. Passing Infinity will flat the whole nested array.

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

console.log(arr.flat(Infinity))

Different approaches to flatten arrays

  1. Recursion

  2. flat() method

2 views