DEV Community

Samantha Ming
Samantha Ming

Posted on β€’ Edited on β€’ Originally published at samanthaming.com

17 8

Flatten Array using Array.flat() in JavaScript

CodeTidbit by SamanthaMing.com

It was always complicated to flatten an array in #JavaScript. Not anymore! ES2019 introduced a new method that flattens arrays. And there's a "depth" parameter, so you can pass in ANY levels of nesting. AMAZING 🀩

const nested = [ ['πŸ“¦', 'πŸ“¦'], ['πŸ“¦']];

const flattened = nested.flat();

console.log(flattened);
// ['πŸ“¦', 'πŸ“¦', 'πŸ“¦']
Enter fullscreen mode Exit fullscreen mode

Setting depth parameter

Here's the syntax for this method:

array.flat(<depth>);
Enter fullscreen mode Exit fullscreen mode

By default, flat() will only flatten one layer deep. In other words, depth is 1.

array.flat();

// Same as

array.flat(1);
Enter fullscreen mode Exit fullscreen mode

Deeper Nested Arrays

The great thing is that this method also works beyond 1 level deep. You simply have to set the appropriate depth parameter to flatten deeper nested arrays.

const twoLevelsDeep = [[1, [2, 2], 1]];

// depth = 1
twoLevelsDeep.flat()
// [1, [2, 2], 1]

// depth = 2
twoLevelsDeep.flat(2)
// [1, 2, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Infinitely Nested Arrays

Let's say, you want to go infinitely deep. Not a problem, we can do that too. Just pass Infinity.

const veryDeep = [[1, [2, 2, [3,[4,[5,[6]]]]], 1]];

veryDeep.flat(Infinity);
// [1, 2, 2, 3, 4, 5, 6, 1]
Enter fullscreen mode Exit fullscreen mode

Array with Empty Slots

One other cool thing that flat() can do is remove empty slots in an array.

const missingNumbers = [1, ,3, ,5];

missingNumbers.flat();
// [1, 3, 5];
Enter fullscreen mode Exit fullscreen mode

Browser Support

flat is a super new feature introduced in ES2019, so forget Internet Explorer or Edge. But no surprise there πŸ˜…

Browser Support: flat

Alternative Solution

Since support is not great. Here are some alternative solutions.

ES6 Solution

Here is a ES6 solution. This only work for one level nested array.

const oneLevelDeep = [ [1, 2], [3]];

const flattened = [].concat(...oneLevelDeep);
// [1, 2, 3,]
Enter fullscreen mode Exit fullscreen mode

Older Browser Solution

Here's one for older browser and pre ES6. Again, this only works for one level nested array.

const oneLevelDeep = [ [1, 2], [3]];

const flattened = [].concat.apply([], oneLevelDeep);
// [1, 2, 3,]
Enter fullscreen mode Exit fullscreen mode

Recursion

For arrays with deeper nesting, you can use recursion. Here's the solution from MDN web docs:

var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Community Input

πŸ’¬ Got any interesting use cases of Array.flat()?

  • @hocine_abdellatif: A little far use case but probably worth mentioning, in machine learning if you have for example an array of generations, each generation is an array of students, if you want to have every student from every generation,this method will be very practical.

  • @devjacks: I wrote a code test with a problem like this a few weeks ago. This would have made my life so much easier! πŸ˜‚

// Please write a function to search for 213

function search(needle, haystack) {}

const haystack =[1, 4, [5,6,7, [8, 18, [34,177,[98,[210,[213]]]]]]];
const needle = 213;
Enter fullscreen mode Exit fullscreen mode

Resources


Thanks for reading ❀
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
nickymeuleman profile image
Nicky Meuleman β€’

Array.flatMap() is also a nice shortcut!
It's equivalent to Array.flat(1).map()

Collapse
 
samanthaming profile image
Samantha Ming β€’

Oh cool! I briefly looked into flatMap...I’ll have to cover it in a future tidbit then! πŸ˜†

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more