Javascript ES6 flat() and flatMap()

Here are 2 nice features of Javascript ES6 which I had to use recently.

Array.prototype.flat()

This will create a new array with all sub-array elements concatenated into it recursively up to the specified depth.

  
  
const numberLists = [['one', 'two'], ['three', 'four']];

console.log(numberLists.flat());
// ['one', 'two', 'three', 'four']
  

You can pass the depth number as a parameter

  
  
const numberLists = [['one', 'two'], ['three', 'four', ['five',['six'], 'seven']]];

console.log(numberLists.flat(1));
// ['one', 'two', 'three', 'four', ['five',['six'], 'seven']

console.log(numberLists.flat(2));
// ['one', 'two', 'three', 'four', 'five', ['six'], 'seven']

console.log(numberLists.flat(3));
// ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
  

If you don’t want to specify the depth, you can pass Infinity as parameter.

  
  
const numberLists = [['one', 'two'], ['three', 'four', ['five',['six'], 'seven']]];

console.log(numberLists.flat(Infinity));
// ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
  

 

 

Array.prototype.flatMap()

This will first map each element using a mapping function and then will flatten the result into a new array. Basically flatMap has the same effect as using the map() method followed by the flat() method with the default depth of 1.

  
  
const numbersList = ['one', 'two', 'three', 'four'];
const thingsList = ['ball', 'laptops', 'books', 'letters'];

const mappedList = numbersList.map((numberItem, index) => [numberItem, thingsList[index]]);
console.log(mappedList);
// [['one', 'ball'], ['two', 'laptops'], ['three', 'books'], ['four', 'letters']

const mappedAndFlattenList = numbersList.flatMap((numberItem, index) => [numberItem, thingsList[index]]);
console.log(mappedAndFlattenList);
// ['one', 'ball', 'two', 'laptops', 'three', 'books', 'four', 'letters']
  

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment