DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at cassidoo.co on

7 1 1 2 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

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

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!