JavaScript | array.flatMap()
The array.flatMap() is an inbuilt function in JavaScript which is used to flatten the input array element into a new array.
This method first of all map every element with the help of mapping function, then flattens the input array element into a new array.
Syntax:
var A = array.flatMap(function callback(current_value, index, Array))
{
// It returns the new array's elements.
}
Parameters:
-
callback: This is the function that produces an element for the new array with the help of three arguments, given below:
- current_value: It is the input array elements.
- index:
- It is optional.
- It is the index of the input element.
- Array:
- It is optional.
- It is used when array map is called.
Return Values: It returns a new array whose elements are the return value of the callback function.
Code #1:
<script> // Taking input as an array A having some elements. var A = [ 1, 2, 3, 4, 5 ]; // Mapping with map function. b = A.map(x => [x * 3]); document.write(b); // Mapping and flatting with flatMap() function. c = arr1.flatMap(x => [x * 3]); document.write(c); // Mapping and flatting with flatMap() function. d = arr1.flatMap(x => [[ x * 3 ]]); document.write(d); </script> |
Output:
[[3], [6], [9], [12], [15]] [3, 6, 9, 12, 15] [[3], [6], [9], [12], [15]]
Code #2: This flatting can also be done with the help of reduce and concat.
<script> // Taking input as an array A having some elements. var A = [ 1, 2, 3, 4, 5 ]; array.flatMap(x => [x * 3]); // is equivalent to b = A.reduce((acc, x) => acc.concat([ x * 3 ]), []); document.write(b); </script> |
Output:
[3, 6, 9, 12, 15]
Note: This function is available in Firefox Nightly only.
Recommended Posts:
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Objects in JavaScript
- JavaScript Course | Operators in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- How to include a JavaScript file in another JavaScript file ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



