Javascript FlatMap() And Javascript Flat()


JavaScript introduced two new methods flat(),flatMap() to flatten array of arrays into single one dimensional array. These two methods are under active develoment. Check the browser compatability before using.

flat() and flatMap() method APIs available in Chrome 69 and Mozilla firefox 62,Opera 56.

Table of Contents

JavaScript Array flat():

JavaScript Array flat() method takes depth as a parameter and returns a new single dimensional array by merging all sub-arrays. And depth parameter is optional.

Hava look at the below example

Array flat() without depth parameter:

var array1 = [0, 1, [2, 3]];
array1.flat();
// [0, 1, 2, 3]

var array2 = [0, 1, [2, 3, [4, 5]]];
array2.flat();
// [0,1, 2, 3, [4, 5]]

Array flat() with depth parameter:

var array2 = [0, 1, [2, 3, [4, 5]]];
array2.flat(2);
// [0,1, 2, 3, 4, 5]

Remove empty slots in Array using JavaScript flat():

Array flat removes empty slots in JavaScript arrays

var arrayEmpty = [1, 2, , 4, 5];
arrayEmpty.flat();
// [1, 2, 4, 5]
JavaScript flat and flatMap methods

JavaScript flat and flatMap methods

JavaScript Array flatMap():

Array flatMap() maps elements array using a mapping function and then flatten the array upto depth of 1.

let stringArray = ["Javascript flat()", "flatMap()"];

stringArray.map(x=>x.split(" "));
// [["Javascript","flat()"],["flatMap()"]]

stringArray.flatMap(x => x.split(" "));
// ["Javascript","flat()","flatMap()"]

 

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or linkedn to get in touch with me.

Spread the word

Get free link to download 900+ Material Icons
Avatar
Arunkumar Gudelli

I am One among a million Software engineers of India. I write beautiful markup.I make the Web useful.

Related

Next
Previous