What is Array.flatMap() in Javascript?
Overview
The flatMap function in JS is a method of the Array class. The flatMap function applies the given callback function on every element in the array it is called on, flattens the result by one level, and returns the newly formed array. The syntax of the flatMap function is as follows:
flatMap(function callbackFn(currentValue, index, array) { ... }, thisArg);
Parameters
callbackFnreturns an element for the new array and has the following three parameters:currentValuestores the current element that is to be processed.index(optional) is an integer that specifies the index of the current element that is being processed.array(optional) is the array on which themapis called.
thisArg(optional) is the value that is used for thethisvariable inside thecallbackFn.
Return value
flatMap()returns an array where each element is the return value fromcallbackFnflattened by one level.
Example
The following code describes the usage of the flatMap function:
const arr = [1, 2, 3, 4, 5];const resultflatMap = arr.flatMap(currentValue => [currentValue * currentValue])console.log('Array:', arr);console.log('flatMap Array:', resultflatMap);
In the example above, the callback function (defined using arrow notation) returns an array with a single element. The single element is the square of currentValue. If this callback function is applied on every element of the array (meaning only the map function is applied), it results in [[1], [4], [9], [16], [25]]. Afterward, if the flat function is called with depth 1, then this results in [1, 4, 9, 16, 25]. However, the flatMap function performs both of these operations in a performance-efficient way, yielding the same result.
Free Resources