@singuerinc


2022.07.07 by Nahuel Scotti | 2 min read

The Array, illustrated: .flat()

How does the array flat method works, explained with illustrations.


flat

According to MDN:

"The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth."

Wow wow! Hold your horses cowboy! What that means?...

Ironing JavaScript Arrays

Let us take a group of blog posts that contains categories as an example:

const posts = [
  { id: 1, categories: ["app", "js"] },
  { id: 2, categories: ["pro", "time"] },
];

We want all those categories to be in a single Array. So let us use our friend map to iterate over this Array.

const allCategories = posts.map((p) => p.categories);
// output: [ [ 'app', 'js' ], [ 'pro', 'time' ] ]

See? We have the categories, but they are nested (devs crying).

Here is where flat comes to the rescue (devs cheering):

flat

const flatten = allCategories.flat();
// output: [ 'app', 'js', 'pro', 'time' ]

Boom! Now we have all our categories in one single Array. Sweet. But...

Leo DiCaprio situation

Sometimes you have Arrays, inside an Array, inside an Array, and so on.

const posts = [
  {
    id: 1,
    categories: [
      ["react", "js"],
      ["easy", "5-min"],
    ],
  },
  {
    id: 2,
    categories: [["pro", "10-min"], ["electron"]],
  },
];

flat() with a depth parameter allow us to solve this case too, it can flat infinite amount of nested Arrays:

flat infinity

const categories = posts.map((p) => p.categories);
const flatten = categories.flat(Infinity);
// output: ["react", "js", "easy", "5-min", "pro", "10-min", "electron"];

Unbalanced mamushkas

So far, we have been flattening down to one single Array, but what if we want to flat Arrays that have seveal arrays down to certain depth?

flat with depth

const arr = [["react", "js", "easy"], [["pro", "10-min"]]];
const flatten = arr.flat(1);
// output: ["react", "js", "easy", ["pro", "10-min"]];

Try it

import "./styles.css";

document.getElementById("app").innerHTML = `
<h1>Hello world</h1>
`;

Futher reading

Explore MDN Web Docs, they have tons of examples to deal with different situations:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

  • #array
  • #fp
  • #functional
  • #javascript