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.

On this page

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()"]