DEV Community

Cover image for Smooshing arrays : flat() and flatMap()
Thabi
Thabi

Posted on • Edited on

26 10

Smooshing arrays : flat() and flatMap()

If you want to flatten an array that has sub-arrays, these two methods are helpful. They were introduced in the ES2019 standard. There was a bit of a controversy with the initial name flatten.

Sometimes, we have to deal with data in nested arrays, you can implement the function yourself

function flattenArrays(arrays) {
  const result = []
  arrays.forEach(array => {
    array.forEach(el => {
      result.push(el)
    })
  })
  return result
}

flattenArrays([[5, 10],15, 20]])
// Expect result : [5, 10, 15, 20]
// This function will only flatten one level of arrays 
Enter fullscreen mode Exit fullscreen mode

Luckily Javascript already provides the .flat() array method. Check browser support before using it.

[1,2,3,4,5,6,7,8,9,[10,11,12],13,14,15].flat()
// Expect result : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Enter fullscreen mode Exit fullscreen mode

.flat() only flattens one level of arrays. Nested arrays deeper than one level are left unmodified.


[1,2,[[3,4],5],6,7,8,9,[10,11,12]].flat()

// Expect result: [1, 2, [3, 4], 5, 6, 7, 8, 9, 10, 11, 12]
Enter fullscreen mode Exit fullscreen mode

You can flatten beyond the first level, the default depth is 1. The depth can also be Infinity to flatten all arrays.

//flatten two levels deep
 [1,2,[[3,4],5],6,7,8,9,[10,11,12]].flat(2)
//Expect result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Enter fullscreen mode Exit fullscreen mode

The depth can be Infinity, in which case flat will flatten all arrays no matter how deeply nested they are.

[[[1]],[[[2]]],[3]].flat(Infinity)
//Expect result: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
  • Note: The flat method only flattens arrays and stops when it is a non-array value. If there are arrays inside an object, it will skip them.
[{ item:'shirt', stockIds: [124,12,145,12,33]}, [121,[2],[1]].flat(Infinity)
/* Expect result: [{
  item: "shirt",
  stockIds: [124, 12, 145, 12, 33]
}, 121, 2, 1] */
Enter fullscreen mode Exit fullscreen mode

.flat() is so commonly used with .map() that a .flatMap() method was created.

Imagine if you sold paint, and you had a tracking system that allows you to save different colours for each brand. You might want to write a list of every colour you have in stock regardless of the brand.

const paintBrands = [
  {name: 'Dulux', colours: ['red', 'white', 'green', 'yellow']},
  {name: 'Berger', colours: ['grey', 'orange']}
]
paintBrands.flatMap(stock => stock.colours)
//Expect result: ["red", "white", "green", "yellow", "grey", "orange"]
Enter fullscreen mode Exit fullscreen mode
  • Note: .flatMap only flattens to 1 depth.

If you have any interesting use-cases for these methods please share below. Thanks for reading.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay