• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Flatten an array in Javascript

Posted Jun 24, 2023 โ€” Updated Jan 10, 2024

Flattening an array means making it one-dimensional. The easiest way to flatten an array is via Array.prototype.flat.

// multi-dimensional array
const multiDimensional = [1, 2, [3, 4]];

// flat, one-dimensional array
const oneDimensional = [1, 2, 3, 4];

For many years, doing this in javascript required the use of concat, spread, or reduce. Not anymore.

Flatten with Array.prototype.flat

This method does exactly what you’d expect:

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

const oneDimensional = multiDimensional.flat();
// [1, 2, 3, 4]

By default, flat only flattens one level deep:

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

// [3, 4] is nested two levels deep
multiDimensional.flat();
// [1, 2, [3, 4]]

But flat accepts an argument specifying depth:

const multiDimensional = [1, [2, [3, 4]]];
multiDimensional.flat(2);
// [1, 2, 3, 4]

That’s it!


Helpful Links

  • Other ways to flatten an array – flexiple

Filed Under: Arrays, Javascript

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 ยท Contact me at justin [at] {this domain}

  • Privacy Policy