Array.flatMap() in javascript

In previous blog, we learn about Array.prototype.flat() function. In this blog we will learn about Array.flatMap() or Array.prototype.flatMap() function.

Introduction

Array.prototype.flatMap() function first maps each element using mapping function. Like Array.prototype.map() function do then after the result are flattens into a new array with depth 1.

In short

Array.prototype.flatMap() = array.prototype.map().flat(1)

Syntax

// Arrow Function Syntax
arrayObject.flatMap((currentValue, [index], [arrayObj]) => { ... } )
// Callback Function Syntax
arrayObject.flatMap(callbackFunction, thisArg)

function callbackFunction(currentValue, [index], [arrayObj]) {

}
// Anonymous Function Syntax
arrayObject.flatMap((currentValue, [index], [arrayObj]) => { ... }, thisArg)

In the syntax

  • currentValue is current element which is being processed.
  • index is current element's index which is being processed which is optional parameter.
  • arrayObj is current array for which flatMap is called.
  • thisArg is a value which is use to this when executing the callback

Example

var arr = [1, 2, 3, 4, 5]

result1 = arr.map(currentValue=>[currentValue, currentValue + 10])

//result1 will be 
// [Array(2), Array(2), Array(2), Array(2), Array(2)]
// 0 : (2)[1, 11]
// 1 : (2)[2, 12]
// 2 : (2)[3, 13]
// 3 : (2)[4, 14]
// 4 : (2)[5, 15]

result2 = arr.flatMap(currentValue=>[currentValue, currentValue + 10])
//result2 will be
// [1, 11, 2, 12, 3, 13, 4, 14, 5, 15]

//As we have already discussed that flatMap is array map + flat so

result3 = result1.flat()
//result2 will be
// [1, 11, 2, 12, 3, 13, 4, 14, 5, 15]

Note

Array.prototype.flatMap() function is available nodejs version 11. And still it is not supported by Internet Explorer. For that you can use Polyfill.

Browser compatibility of Array.prototype.flatMap()

Ployfill for Array.prototype.flatMap()

😊😊😊

Sourabh Somani
He is Microsoft MVP & C# Corner MVP. His core competencies include Mobile and web applications development using .NET, Python, Node.js, C#, JavaScript, jQuery, SQL Server, NoSQL, MongoDB, and Angular.
Chittorgarh, Rajasthan, India