DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at cassidoo.co on

7 1 1 1 1

What does it mean to flatten an array?

When you have an array that has multiple dimensions, it might be referred to as a 2D or 3D (etc) array. If you wanted to turn said array into a 1D array, that is when you flatten it.

More simply, flattening an array refers to the process of converting a multidimensional array into a single dimensional array.

Examples of array flattening

If you want to see some examples of this, here’s some arrays:

[1, [2, [3, [4]]]

[1, [2, 3], 4]

[1, 2, [3], [4]]

[[1, 2], [], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

Every single one of these arrays would be flattened into [1, 2, 3, 4]!

When and why would I flatten something?

Ultimately, flattening is a way to simplify data.

If you want to see a real-world example, you can check out how I set up gathering tags on my blog!

const allTags = posts
  .map((post) => {
    const postTags = post.data.tags;
    let allTags = [];

    if (postTags?.length > 0) {
      postTags.forEach((tag) => {
        if (allTags?.indexOf(tag) === -1) {
          allTags.push(tag);
        }
      });
    }
    return allTags;
  })
  .flat(1);
Enter fullscreen mode Exit fullscreen mode

This is what’s happening:

  • For each blog post post, it checks if post.data.tags exists and has tags
  • It makes an array allTags for each post, and pushes unique tags into it, and returns that array
  • After mapping, we have an array of arrays (one array of tags per post)
  • .flat(1) merges all of those arrays into a single array

Here’s an example input:

const posts = [
  { data: { tags: ["js", "react", "web"] } },
  { data: { tags: ["react", "css"] } },
  { data: { tags: ["node", "js"] } },
  { data: { tags: [] } },
  { data: { tags: ["css", "web"] } },
];
Enter fullscreen mode Exit fullscreen mode

After mapping and flattening, we’d get this:

["js", "react", "web", "react", "css", "node", "js", "css", "web"];
Enter fullscreen mode Exit fullscreen mode

With this flattening, you could more simply count how many posts use a certain tag, or look at how many unique tags there are, or manipulate it in some other way (in my own blog, I make a Set out of the array to just get all unique tags).

Here is the real-life code if you’d like to see it in context!

This might seem like a simple concept, but it’s a handy one.

If you’d like to do this in JavaScript here’s the documentation. The flat() function (as well as flatMap()) was introduced in ES2019 (so browser compatibility is pretty good unless you reeeaally need Internet Explorer), but you can also achieve the same results with reduce(), concat(), and some other functions.

Byyyye <3

Neon image

⚡ Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (2)

Collapse
 
best_codes profile image
Best Codes

Great explanation. I flatten arrays all the time but didn't know you actually call it that. Thanks for the write-up!

Collapse
 
jance_jacobs profile image
Jance Jacobs

Super clear explanation—love the examples!

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Sign in to DEV to enjoy its full potential—unlock a customized interface with dark mode, personal reading preferences, and more.

Okay