The Javascript array flatMap() is an inbuilt method in JavaScript that is used to flatten the input array element into a new array. This method first of all maps every element with the help of a mapping function, then flattens the input array element into a new array.
Syntax:
let A = array.flatMap(function callback(current_value, index, Array)) {
// It returns the new array's elements.
}
Parameters:
- current_value: It is the input array element.
- index:
- It is optional.
- It is the index of the input element.
- Array:
- It is optional.
- It is used when an array map is called.
Return Values: It returns a new array whose elements are the return value of the callback function.
Example 1: in this example, we will see the basic use of the array.flatMap() method for flattening an array.
javascript
let A = [1, 2, 3, 4, 5];
b = A.map(x => [x * 3]);
console.log(b);
c = A.flatMap(x => [x * 3]);
console.log(c);
d = A.flatMap(x => [[x * 3]]);
console.log(d);
|
Output
[ [ 3 ], [ 6 ], [ 9 ], [ 12 ], [ 15 ] ]
[ 3, 6, 9, 12, 15 ]
[ [ 3 ], [ 6 ], [ 9 ], [ 12 ], [ 15 ] ]
Example 2: This flatting can also be done with the help of reducing and concat.
javascript
let A = [1, 2, 3, 4, 5];
console.log(A.flatMap(x => [x * 3]))
b = A.reduce((acc, x) => acc.concat([x * 3]), []);
console.log(b);
|
Output
[ 3, 6, 9, 12, 15 ]
[ 3, 6, 9, 12, 15 ]
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Supported Browser:
- Google Chrome 69 and above
- Edge 79 and above
- Firefox 62 and above
- Opera 56 and above
- Safari 12 and above
Note: This method is available in Firefox Nighty only.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 May, 2023
Like Article
Save Article