Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is Array.flatMap() in Javascript?

Hammad Nasir

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

  • callbackFn returns an element for the new array and has the following three parameters:
    • currentValue stores 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 the map is called.
  • thisArg (optional) is the value that is used for the this variable inside the callbackFn.

Return value

  • flatMap() returns an array where each element is the return value from callbackFn flattened 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.

RELATED TAGS

javascript

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring