Flatten Array using Array.flat() in JavaScript

Flatten Array using Array.flat() in JavaScript

Flatten Array using Array.flat() in JavaScript

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);
// ['πŸ“¦', 'πŸ“¦', 'πŸ“¦']

Setting depth parameter

Here's the syntax for this method:

array.flat(<depth>); 

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

array.flat();

// Same as

array.flat(1);

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()
// [1, 2, 2, 1]

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]

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];

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,]

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,]

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]

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;

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.