Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Fri May 12 2023

How to flatten arrays in JavaScript

In this guide we will show how to flatten arrays in JavaScript. We will show examples of arrays of numbers and arrays of objects and how we can make the arrays easier to handle when they are nesting other arrays.

Array.flat()

In JavaScript, there is a built in function called flat() that we can use, and it is also available in Node version > 11. It takes an argument, which is the depth it will flatten, by default it is 1.

Example of one level nesting

Let's start with a basic example

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

Let's add another level. In below example, it will only flatten the inner array one level, so it will still have a nested array but with one level instead of two.

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

Add manual depth

Let's add a depth argument to the function to solve above issue

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

And now it will be completely flattened.

Object arrays flattening

Let's create some arrays with objects and see how we can work with them as well.

const arr = [[{ name: "Peter" }], [{ name: "Lisa" }]]; arr.flat(); // [{"name":"Peter"},{"name":"Lisa"}]

Above example works exactly as our number arrays.

But how about this one? Will it take care of the inner array? Let's see...

const arr = [ { name: "Peter", hobbies: ["Football", "Tennis", ["Golf"]], }, ]; arr.flat(); // [{"name":"Peter","hobbies":["Football","Tennis",["Golf"]]}]

It will not...

When it comes to these nested inner arrays of the array, we need to map it into a new array where we flat the properties in the map function. Example:

const arr = [ { name: "Peter", hobbies: ["Football", "Tennis", ["Golf"]], }, ]; const result = arr.map((obj) => ({ ...obj, hobbies: obj.hobbies.flat(), })); // [{"name":"Peter","hobbies":["Football","Tennis", "Golf"]}]

And now it is flattened. By iterating over the objects and re-mapping the objects we can take care of the nested arrays in the objects as well.

There are nice utilities in for example Lodash library that can be downloaded from NPM that has deepFlatten functions that will fix this automatically, but sometimes it can be great to know what is going on under the hood and to solve things ourselves.

Outro

I will end this guide here. I hope you found this useful, and a big thanks for reading.

Have a great day!

signatureFri May 12 2023
See all our articles