Horje
What is Array.flatMap() in JavaScript?

Array.flatMap() is a method introduced in ECMAScript 2019 (ES10) that combines the functionalities of map() and flat() methods. It first maps each element of an array using a mapping function, then flattens the result into a new array. This method is particularly useful when you want to apply a transformation to each element of an array and flatten the resulting arrays into a single array.

Syntax:

array.flatMap(callbackFn[, thisArg])

Parameters:

  • callbackFn: A function that accepts up to three arguments: the current element being processed, the index of the current element, and the array being mapped.
  • thisArg (optional): An object to which this a keyword can refer to inside the callbackFn.

Example: Here, the flatMap() method is called on the arr array with a callback function that doubles each element of the array and creates a new array containing both the original element and its doubled value.

Javascript

const arr = [1, 2, 3];
 
const result = arr.flatMap(x => [x, x * 2]);
 
console.log(result);

Output

[ 1, 2, 2, 4, 3, 6 ]





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What is Object.defineProperty() in JavaScript? What is Object.defineProperty() in JavaScript?
What is Array.join() method in JavaScript? What is Array.join() method in JavaScript?
What is function scope in JavaScript? What is function scope in JavaScript?
How to use innerHTML in JavaScript ? How to use innerHTML in JavaScript ?
What is block scope in JavaScript? What is block scope in JavaScript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14