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]]
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);
This is what’s happening:
- For each blog post
post
, it checks ifpost.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"] } },
];
After mapping and flattening, we’d get this:
["js", "react", "web", "react", "css", "node", "js", "css", "web"];
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
Top comments (2)
Great explanation. I flatten arrays all the time but didn't know you actually call it that. Thanks for the write-up!
Super clear explanation—love the examples!